I needed a way to escape special regex characters in a string. These characters include the following: “.”, “$”, “^”, “{“, “[“, “(“, “|”, “)”, “*”, “+”, “?”, “\\” . This list was obtained from http://msdn.microsoft.com/en-us/library/4edbef7e(v=vs.110).aspx
Here is a small string extension method that will accomplish this:
Edit*- 1/24/13 – I didn’t realize there was a built in method in the Regex library to do just this. I feel stupid, but anyhow, here is the revised extension method none the less :)
public static string EscapeCharactersForRegEx(this string instance) { return Regex.Escape(instance); }
Now all special regex characters in your string should be escaped. Feedback always welcome! Thanks!
But you’re escaping white spaces with Regex.Escape too.
What if I don’t want to escape it.