我正在对一些数据进行正则表达式,如果 $_ 在"替换"部分中,我也会收到内容。 我已经为$replace尝试了各种方法,但似乎无法阻止这种行为。 我也尝试了 [regex]::escape() 但是最终做了同样的事情,只是使用转义字符。
我需要能够容忍 $_ 代替。 我可以让它变成别的东西,稍后再做一个修复,但这很丑陋,我宁愿避免它。
最后,如果 $replace='$anythingelse' 它似乎按预期运行,只有 $_ 似乎会导致此问题。 如果可以禁用所有解析,那也将起作用。
脚本:
$contents = 'foo' $replace = '$_ bar' $final = $contents -replace 'oo', $replace Write-Output "Contents: $contents" Write-Output "Replace: $replace" Write-Output "Final: $final"
输出:
Contents: foo Replace: $_ bar Final: ffoo bar
系统: 视窗 7, PSH 2, 64 位
那么我做错了什么还是这真的是一个错误?
编辑 6/29:
我做了一个替换,所以我可以进行更换。 这很愚蠢,应该有一种方法可以禁用解析(这也会使它的运行速度略快)。
$contents = 'foo' $replace = '$_ bar' **$rep = $replace -replace '$','$$$'** $final = $contents -replace 'oo', $rep Write-Output "Contents: $contents" Write-Output "Replace: $replace" Write-Output "Final: $final"
输出
Contents: foo Replace: $_ bar Final: f$_ bar
您的问题是替换字符串中的"$_"表示整个输入字符串。如果你想要一个字面上的美元符号,你需要使用 $$ 对其进行转义:
$replace = '$$_ bar'
有关详细信息,请参阅 msdn 上的替换页面!
编辑以解决问题编辑 29/6
如果您想要的只是没有任何正则表达式的基本字符串替换,只需使用标准字符串替换而不是-replace
:
$final = $contents.replace('oo', $replace)
我使用以下命令来做到这一点:
`$$`_