如果您想删除所有超出 ASCII 范围的字符(Unicode 代码点范围 U+0000 - U+007F):
PowerShell (Core) 7+解决方案:
# Removes any non-ASCII characters from the LHS string,
# which includes the problematic hidden control characters.
'S0841488.JPG0608201408.21' -replace '\P{IsBasicLatin}'
该解决方案使用基于正则表达式的-replace operator,以及Unicode block nameIsBasicLatin 的否定形式(\P),它指的是Unicode 的ASCII 子范围。简而言之:\P{IsBasicLatin} 匹配任何非 ASCII 字符,并且由于没有指定替换字符串,因此有效地删除它;结合-replace 总是替换输入字符串中的 all 匹配项,所有非 ASCII 字符都将被删除。
Windows PowerShell解决方案:
令人难以置信的是,Windows PowerShell 中的一个错误(从 v5.1.19041.1023 开始;v5.1.x 是最新的最终版本)源自底层 .NET Framework 4.8.4390.0, 错误地认为 ASCII 范围 i / I 超出了 ASCII 范围,因此将其删除; 解决方法:
# WORKAROUND for Windows PowerShell to prevent removal of 'I' / 'i'
'Ii-S0841488.JPG0608201408.21' -replace '[^i\p{IsBasicLatin}]'
您可以验证这有效地从您的字符串中删除(不可见的)从左到右标记U+200E 和从右到左标记U+200F 字符Debug-String 函数,可用作an MIT-licensed Gist:
# Download and define the Debug-String function.
# NOTE:
# I can personally assure you that doing this is safe, but you
# you should always check the source code first.
irm https://gist.github.com/mklement0/7f2f1e13ac9c2afaf0a0906d08b392d1/raw/Debug-String.ps1 | iex
# Visualize the existing non-ASCII-range characters
'S0841488.JPG0608201408.21' | Debug-String -UnicodeEscapes
# Remove them and verify that they're gone.
'S0841488.JPG0608201408.21' -replace '\P{IsBasicLatin}' | Debug-String -UnicodeEscapes
以上结果如下:
S0841488.JPG06082014`u{200f}`u{200e}08.21
S0841488.JPG0608201408.21
注意原始输入字符串中不可见的控制字符`u{200f} 和`u{200e} 的可视化,以及应用-replace 操作后它们如何不再存在。
在 PowerShell (Core) 7+(但不是 Windows PowerShell)中,此类 Unicode 转义序列也可用于可扩展字符串,即在双引号字符串文字中(例如,"Hi`u{21}" 逐字扩展为 Hi!)-请参阅概念性的 about_Special_Characters 帮助主题。