Powershell -replace 当替换字符串包含 $+ [英] Powershell -replace when replacement string contains $+
问题描述
我正在 PowerShell 中进行字符串替换.我无法控制被替换的字符串,但我可以通过这种方式重现我遇到的问题:
I am doing a string replacement in PowerShell. I have no control over the strings that are being replaced, but I can reproduce the issue I'm having this way:
> 'word' -replace 'word','@#$+'
@#word
当我需要的实际输出是
> 'word' -replace 'word','@#$+'
@#$+
字符串 $+
被扩展为被替换的单词,我无法找到阻止这种情况发生的方法.我试过用 \
转义 $
(好像它是一个正则表达式),用反引号 `
(这是正常的PowerShell方式).例如:
The string $+
is being expanded to the word being replaced, and there's no way that I can find to stop this from happening. I've tried escaping the $
with \
(as if it was a regex), with backtick `
(as is the normal PowerShell way). For example:
> 'word' -replace 'word',('@#$+' -replace '\$','`$')
@#`word
如何在 PowerShell 中用文字 $+
替换?值得一提的是,我正在运行 PowerShell Core 6,但这也可以在 PowerShell 5 上重现.
How can I replace with a literal $+
in PowerShell? For what it's worth I'm running PowerShell Core 6, but this is reproducible on PowerShell 5 as well.
推荐答案
你可以像这样使用 .Replace()
方法,而不是使用 -replace
操作符:
Instead of using the -replace
operator, you can use the .Replace()
method like so:
PS> 'word'.Replace('word','@#$+')
@#$+
.Replace()
方法来自 .NET String 类,而 -Replace
运算符是使用 System.Text.RegularExpressions.Regex.Replace 实现的()
.
The .Replace()
method comes from the .NET String class whereas the -Replace
operator is implemented using System.Text.RegularExpressions.Regex.Replace()
.
此处的更多信息:https://vexx32.github.io/2019/03/20/PowerShell-Replace-Operator/
这篇关于Powershell -replace 当替换字符串包含 $+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!