一种 Select 是使用100-based 101 operation based on 102:
"Helloäöü€?→" -creplace '[^\p{IsBasicLatin}\p{IsLatin-1Supplement}–—€‚‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•˜™š›œžŸ]'
由于您的输入已经是.NET字符串(因此由UTF-16代码单元组成),因此不需要严格地在字节之间进行转换:
通过将所有non匹配的(^
)字符替换为(隐含的)empty string,所有非Windows-1252字符实际上都是removed.
一个一般性的警告:
- 由于在命令中使用了literal个非ASCII范围的字符,请确保PowerShell正确解释脚本文件的字符编码,这特别意味着使用UTF-8文件with BOM来支持Windows PowerShell-请参见this answer.
然而,your to-and-from-bytes encoding approach can be used with a slight adaptation,这是works with any target encoding(不需要列举如上的单个字符):
使用用empty string初始化的System.Text.EncoderReplacementFallback
实例可以有效地删除目标编码中无法表示的所有字符.
$string = "Helloäöü€?→"
$encoding = [System.Text.Encoding]::GetEncoding(
1252,
# Replace non-Windows-1252 chars. with '' (empty string), i.e. *remove* them.
[System.Text.EncoderReplacementFallback]::new(''),
[System.Text.DecoderFallback]::ExceptionFallback # not relevant here
)
$string = $encoding.GetString($encoding.GetBytes($string))