powershell:如何从字符串中转义所有正则表达式字符 [英] powershell: how to escape all regex characters from a string

查看:299
本文介绍了powershell:如何从字符串中转义所有正则表达式字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 "\)","\)"


推荐答案

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

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 '[[+*?()\\.]','\$&'

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

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

这篇关于powershell:如何从字符串中转义所有正则表达式字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆