Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Wednesday, February 15, 2012 7:40 PM | 1 vote
Hi!
I'm looking for a way to replace a string in a file but without powershell interpreting the search string as a regex pattern.
The reason is that the parameters for the search and replace operation are coming from another source and it can happen that the search parameter will contain characters that powershell will interprets as a regex pattern.
Currently I'm doing my search and replace operation like this:
(Get-Content $filepath) | Foreach-Object {$_ -replace $string2find, $replacewith} | Set-Content $filepath;
An alternative would be to escape the $string2find parameter so that all special regex characters get escaped. However I was unable to find such a function build in.
br
Stefan
All replies (3)
Wednesday, February 15, 2012 7:43 PM ✅Answered | 2 votes
$_ -replace [regex]::escape($string2find),$replacewith
Wednesday, February 15, 2012 7:45 PM ✅Answered
The escape function is a static function. It won't show up on a get-member unless you specifially ask for static members, or use -force.
Get-Content $filepath) | Foreach-Object {$_ -replace [regex]::escape($string2find), $replacewith} | Set-Content $filepath
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "
Wednesday, February 15, 2012 7:44 PM
$_ -replace [regex]::escape($string2find),$replacewith
thank you! that did the trick :)
br
Stefan