我在Excel中使用vlookup时遇到了一些问题。 我已经看到了这个问题,但我还没有找到解决方案。
我有一个包含Unicode字符的大量文本文件行。
例如: 这一行:'S0841488.JPG0608201408.21' 包含这两个Unicode字符:U+200F U+200E 'S0841488.JPG06082014 U+200F U+200E 08.21。
请告诉我如何使用Powershell去除这些Unicode字符。
我在Excel中使用vlookup时遇到了一些问题。 我已经看到了这个问题,但我还没有找到解决方案。
我有一个包含Unicode字符的大量文本文件行。
例如: 这一行:'S0841488.JPG0608201408.21' 包含这两个Unicode字符:U+200F U+200E 'S0841488.JPG06082014 U+200F U+200E 08.21。
请告诉我如何使用Powershell去除这些Unicode字符。
# Removes any non-ASCII characters from the LHS string,
# which includes the problematic hidden control characters.
'S0841488.JPG0608201408.21' -creplace '\P{IsBasicLatin}'
-creplace
,这是基于正则表达式的-replace
操作符的区分大小写的变体[1],使用了Unicode块名称IsBasicLatin
的否定形式(\P
)。它指的是Unicode的ASCII子范围。简而言之:\P{IsBasicLatin}
匹配任何非ASCII字符,并且由于没有指定替换字符串,它有效地删除它;结合-creplace
在输入字符串中无论如何都会替换所有匹配项,所有非ASCII字符都被删除。U+200E
和右到左标记U+200F
字符。该函数是作为一个MIT许可的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
操作后,它们不再存在。"Hi`u{21}"
扩展为直接输出Hi!
)- 请参阅概念性about_Special_Characters帮助主题。
\P{L}
正则表达式块名称构造仍然排除小写字母(而\P{Lu}
/ \P{Ll}
只会排除大写字母/小写字母)。'"Véronique & “Cheris"' -creplace '[^\p{IsBasicLatin}\p{IsLatin-1Supplement}]'
。 - undefined# Path to your file and new file where no unicode characters.
$Path = "C:\JustForExample\FileThatContainsThisLines.txt"
$NewPath = "C:\JustForExample\FileThatContainsThisLines2.txt"
# Getting content of file.
$content = Get-Content -Path $Path
# Removing unicode characters.
$newContent = $content -replace "\s?U\+200[EF]\s?"
# For removing quot and dot at the end.
$newContent = $newContent -replace "('|\.$)"
# Saving content to new Path.
# If you need to replace them inside the file, so just change NewPath to Path.
$newContent | Set-Content -Path $NewPath
所以,替换简单应该删除与该模式匹配的内容。
U+200F
这样的东西只是对那些字符的“可视化”,它们本身是“不可见”的。如果你复制并粘贴问题中“这一行:”后面的字符串,你将得到一个包含这些隐藏字符的字符串。 - mklement0i
/ I
问题:你触发了一个严重的错误,在 Windows PowerShell 中已经得到修正,在 PowerShell (Core) 中请参考我的更新答案。 - mklement0