-replace不会用"()"替换字符串。

时间:2016-08-23 12:31:07

标签: powershell

我试图在PowerShell中替换包含括号的字符串。但是,当我尝试这样做时,它无法正常工作。

知道我哪里出错了吗?我想在PowerShell中用()替换包含-replace的字符串?

$a='Some Text with (round) brackets. This text is long.'
$ch="with (round) brackets."
$b="this text"
$a -replace $ch,$b

输出:

Some Text with (round) brackets. This text is long.

2 个答案:

答案 0 :(得分:6)

-replace使用正则表达式,因此您必须转义您的regex

$a='Some Text with (round) brackets. This text is long.'
$ch="with (round) brackets."
$b="this text"
$a -replace [regex]::Escape($ch),$b

<强>输出:

Some Text this text This text is long.

答案 1 :(得分:2)

将转义字符\添加到字符串:

$ch="with \(round\) brackets."
$b="this text"
$a -replace $ch,$b

Some Text this text This text is long.

或使用

[Regex]::Escape($ch),$b