tl;dr:
加倍替换操作数中的$ 以使用它逐字逐句:
PS> 'word' -replace 'word', '@#$$+' # note the doubled '$'
@#$+
PowerShell 的-replace operator:
如果both您的搜索字符串和您的替换字符串逐字,请考虑使用[string]类型的@改为987654324@,如Brandon Olin's helpful answer所示。
-
警告:.Replace() 默认区分大小写,而-replace 不区分大小写(作为 PowerShell 一般是);使用不同的.Replace() 重载来区分大小写,或者相反,使用PowerShell 中的-creplace 变体来区分大小写。
-
[PowerShell (Core) 7+ only] 大小写-不敏感
.Replace() 示例:
'FOO'.Replace('o', '@', 'CurrentCultureIgnoreCase')
-
.Replace() 只接受一个单个字符串作为输入,而-replace接受一个字符串数组 > 作为 LHS;例如:
'hi', 'ho' -replace 'h', 'f' # -> 'fi', 'fo'
-
.Replace() 比 -replace 快,尽管这只在迭代次数较多的循环中很重要。
如果您坚持使用 -replace 运算符:
如上所述,加倍替换操作数中的 $ 可确保在替换操作数中逐字处理它们:
PS> 'word' -replace 'word', '@#$$+' # note the doubled '$$'
@#$+
要以编程方式进行这个简单的转义,您可以利用.Replace() 方法:
'word' -replace 'word', '@#$+'.Replace('$', '$$')
你也可以用 nested -replace 操作来做到这一点,但这会变得笨拙(\$ 在正则表达式中转义 $;$$ 表示 单个 $ 在替换字符串中):
# Same as above.
'word' -replace 'word', ('@#$+' -replace '\$', '$$$$')
换一种说法:相当于:
'word'.Replace('word', '@#$+')
是(注意-replace 运算符-creplace 的大小写敏感变体的使用):
'word' -creplace [regex]::Escape('word'), '@#$+'.Replace('$', '$$')
但是,如上所述,如果要逐字使用搜索字符串和替换操作数,则最好使用.Replace(),既简洁又性能好。