我正在对某些数据进行正则表达式,如果$ _在“替换”部分中,我也将获取内容。我为$ 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
系统:Windows 7,PSH 2,64bit
那么我是在做错什么还是真的是错误?
编辑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上的substitutions页面!
编辑以解决问题编辑29/6
如果您只需要基本字符串替换而无需任何正则表达式,则只需使用标准字符串替换而不是
-replace
即可:$final = $contents.replace('oo', $replace)
关于regex - Powershell替换中可能存在错误,还是我做错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11254309/