Powershell: Escape a String for regular expression.


when a pattern for a regular expression contains reserved characters it can be difficult to quote all these signs correctly.

A .NET function helps 🙂

Let us assume you want to parse a HTML Site for download links. The lines with the link have the format

<li><a href="http://cert.mydomain.org/pki/Cert0001.crt" target="_blank">download</a></li>

Characters like “.” or Spaces must be escaped. The function Escape() from the RegEx class helps:

$sLink='<li><a href="http://cert.mydomain.org/pki/Cert0001.crt" target="_blank">download</a></li>'

<li><a\ href="http://cert\.mydomain\.org/pki/Cert0001\.crt"\ target="_blank">download</a></li>

And then its simply to extract the download link(all crt files from cert.mydomain.org) :

<li><a\ href="(http://cert\.mydomain\.org/pki/.+\.crt)"\ target="_blank">download</a></li>

[System.Text.RegularExpressions.Regex]::Match($sLink, $sPattern).Groups[1].Value


Advertisment to support michlstechblog.info

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.