I had a case today where I needed to “escape” characters which were to be built as part of a regular expression string. This was required in case the string built into the regular expression used any “reserved” characters used by the Regex engine.
Below is the code used in C# and JavaScript notation:
C#:
private string EscapeRe(string text)
{
return Regex.Replace(text, @"[.*+?^${}()|[]/]", "$0");
}
JavaScript:
[sourcecode language='jscript']
function encodeRE(s) { return s.replace(/[.*+?^${}()|[]/]/g, ‘$0′); }
Very handy!
JavaScript version courtesy of Tino Zijdel who posted on http://simonwillison.net/2006/Jan/20/escape/.
Post a Comment