2016-08-23 174 views
1

我試圖替換包含在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. 

回答

3

-replace useses 正則表達式所以你必須要逃生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

正是我一直在尋找!萬分感謝! –

+0

再次嗨!任何想法,我怎麼也可以處理$ a =「一些帶有圓括號的文本,這段文字很長。」 –

+0

我的意思是'符號 –

2

添加轉義字符\字符串:

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

Some Text this text This text is long. 

或者使用

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