powershell:如何从字符串中转义所有regex字符

时间:2022-05-28 22:28:43

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

我想知道在powershell中是否有更好的选项来转义regex字符,我知道c#有regex。Escape,但是我不确定powershell是否有自己的方法……

This is what I am doing at the moment:

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

$escapedStr = $regexStr -replace "\+","\+" -replace "\[","\[" -replace "\]","\]" -replace "\(","\(" -replace "\)","\)"

1 个解决方案

#1


16  

PowerShell can call the exact same method:

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

[Regex]::Escape($regexStr)

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

但是您甚至可以通过使用一个regex替换来改进您的替换:

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

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

但是,我可能仍然忽略了字符类中的一些元字符,因此只需使用[regex]: Escape方法。

#1


16  

PowerShell can call the exact same method:

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

[Regex]::Escape($regexStr)

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

但是您甚至可以通过使用一个regex替换来改进您的替换:

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

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

但是,我可能仍然忽略了字符类中的一些元字符,因此只需使用[regex]: Escape方法。