Powershell 2:如何从 ASCII 文本正文中去除特定字符

Lar*_*old 5 powershell unicode regular-expressions ascii

我正在尝试使用 PowerShell 从字符串中去除奇数字符。我使用以下输出尝试自己学习:

get-help about_regular_expressions
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取一个主要是 ASCII 的字符串,但它有一个需要删除的异常字符。(注册商标符号;R 周围有一个圆圈。)我想从字符串中删除该字符的任何出现,保持其他所有内容完好无损。使用 PowerShell 2.0 完成此操作的最简洁的表达式是什么?

[编辑]

我做了一些进一步的挖掘,我相信问题源于我正在使用的 Import-CSV 调用。

当我将此符号从记事本中剪切并粘贴到 PS 提示符中,并将其分配给一个字符串时,我匹配得很好:

# This code yields 'True'
$string -match "\u00ae"
Run Code Online (Sandbox Code Playgroud)

但是,当我在其中一个字段包含特殊符号的 CSV 文件上使用 Import-CSV 时,我相信原始字节会以某种方式被转换,因为这样做是行不通的:

# This code yields 'False'
$source = Import-CSV -path testing.csv
# The following extracts the entry / line containing the special symbol that was
# copy-and-pasted above
$culprit = $source[5].COMMITTEE_NAME
$culprit -match "\u00ae"
Run Code Online (Sandbox Code Playgroud)

但是,以下确实有效:

# This yields True
$filedata = get-content testing.csv
$filedata[6] -match "\u00ae"
Run Code Online (Sandbox Code Playgroud)

所以我认为我对所有这些的后续问题是:

如何通过 import-csv 调用保持字符串完整,以便对单个字段的 -match 调用仍然有效?

jsc*_*ott 1

需要注意的是,控制台 PS 不能很好地显示 Unicode。您必须使用 ISE 来“查看”正在发生的情况。看看这个相关的SO问题以获得一些额外的阅读。不管怎样,如果您不需要观看正在运行的脚本,您可以在 PS 中使用 \xc2\xae 字符。

\n\n

在 ISE 中:

\n\n
PS C:\\Users\\jscott> $string = "This string contains the \xc2\xae character"\nPS C:\\Users\\jscott> $string\nThis string contains the \xc2\xae character\n\nPS C:\\Users\\jscott> $string.Replace("\xc2\xae","")\nThis string contains the  character\n\nPS C:\\Users\\jscott> $string ="This \xc2\xae string \xc2\xae contains \xc2\xae many \xc2\xae characters \xc2\xae\xc2\xae\xc2\xae\xc2\xae"\nPS C:\\Users\\jscott> $string\nThis \xc2\xae string \xc2\xae contains \xc2\xae many \xc2\xae characters \xc2\xae\xc2\xae\xc2\xae\xc2\xae\n\nPS C:\\Users\\jscott> $string.Replace("\xc2\xae","")\nThis  string  contains  many  characters \n
Run Code Online (Sandbox Code Playgroud)\n\n

要使用字符代码而不是文字:

\n\n
PS C:\\Users\\jscott> $string.Replace("$([char]0x00AE)","")\n
Run Code Online (Sandbox Code Playgroud)\n\n

根据您的问题更新:

\n\n

在运行之前,您需要将 ASCII 文件转换为 Unicode/UTF8 Import-Csv- 我没有意识到您正在使用它。请大家看看这个这个的其他例子。

\n\n

您可能只想通过管道传送初始 CSV 文件Get-ContentExport-Csv -Encoding Unicode预处理该文件以使生活更轻松。

\n