Regex Escapees

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("|", @"\|");
}
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>