powershell:如何从字符串中转义所有正则表达式字符

Man*_*ros 15 regex powershell

我想知道是否有更好的方法来逃避powershell中的正则表达式字符,我知道C#有Regex.Escape,但我不确定powershell是否有自己的方法......

这就是我现在正在做的事情:

$escapedStr = $regexStr -replace "\+","\+" -replace "\[","\[" -replace "\]","\]" -replace "\(","\(" -replace "\)","\)"
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 28

PowerShell可以调用完全相同的方法:

[Regex]::Escape($regexStr)
Run Code Online (Sandbox Code Playgroud)

但是,您甚至可以通过仅使用一个正则表达式替换来改进您的替换:

$regexStr -replace '[[+*?()\\.]','\$&'
Run Code Online (Sandbox Code Playgroud)

但是,我可能仍然错过了该字符类的一些元字符,所以只需使用该[regex]::Escape方法即可.