Regex Escapees

November 22, 2011 00:00

Sometimes when one writes regexes, Its hard to know what needs to be escaped and what doesn't. But I've solved that problem while I was writing a program that generated my regexes for me. Now I have a snippet that both humans and programs can use to write regexes!

This is for the .NET flavor of Regex.

private static string SanitizeToken(string token) 
{
    return token
                    .Replace(@"\", @"\\")
                    .Replace("*", @"\*")
                    .Replace("?", @"\?")
                    .Replace("+", @"\+")
                    .Replace("{", @"\{")
                    .Replace("}", @"\}")
                    .Replace("^", @"\^")
                    .Replace("$", @"\$")
                    .Replace(".", @"\.")
                    .Replace("[", @"\[")
                    .Replace("]", @"\]")
                    .Replace("(", @"\(")
                    .Replace(")", @"\)")
                    .Replace("|", @"\|");
}