Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

powershell: how to escape all regex characters from a string

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 ")",")"
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...