24

I am wondering if there is a better way to escape regex characters in powershell, I know C# has Regex.Escape, but I'm not sure if powershell has its own method...

This is what I am doing at the moment:

$escapedStr = $regexStr -replace "\+","\+" -replace "\[","\[" -replace "\]","\]" -replace "\(","\(" -replace "\)","\)"
mklement0
  • 382,024
  • 64
  • 607
  • 775
masber
  • 2,875
  • 7
  • 29
  • 49

1 Answers1

44

PowerShell can call the exact same method:

[Regex]::Escape($regexStr)

But you could even improve your replacement by using just a single regex replace:

$regexStr -replace '[[+*?()\\.]','\$&'

However, I probably still missed a few metacharacters from that character class, so just use the [regex]::Escape method.

Joey
  • 344,408
  • 85
  • 689
  • 683