Regex Escapees

| Comments

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private static string SanitizeToken(string token)
{
  return token
                  .Replace(@"\", @"\\")
                  .Replace("*", @"\*")
                  .Replace("?", @"\?")
                  .Replace("+", @"\+")
                  .Replace("{", @"\{")
                  .Replace("}", @"\}")
                  .Replace("^", @"\^")
                  .Replace("$", @"\$")
                  .Replace(".", @"\.")
                  .Replace("[", @"\[")
                  .Replace("]", @"\]")
                  .Replace("(", @"\(")
                  .Replace(")", @"\)")
                  .Replace("|", @"\|");
}

Comments