Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-replace does not replace string with "()"

Tags:

powershell

I'm trying to replace a string containing parentheses in PowerShell. However, when I try this to do this it is not working.

Any idea as to where I'm going wrong? What am I suppose to do to replace a string containing () with -replace in PowerShell?

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

Output:

Some Text with (round) brackets. This text is long.
like image 590
Idris Wishiwala Avatar asked Aug 23 '16 12:08

Idris Wishiwala


2 Answers

-replace useses regular expression so you have to to escape your regex:

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

Output:

Some Text this text This text is long.
like image 77
Martin Brandl Avatar answered Oct 22 '22 09:10

Martin Brandl


Add Escape Character \ to the string:

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

Some Text this text This text is long.

Or use

[Regex]::Escape($ch),$b
like image 23
Avshalom Avatar answered Oct 22 '22 09:10

Avshalom