C# String extension method to escape characters for regular expressions (regex)

C# String extension method to escape characters for regular expressions (regex)

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!

By | 2014-01-24T07:43:31+00:00 January 24th, 2014|Categories: C#, Handy Tools/Utilities|1 Comment

About the Author:

One Comment

  1. Joseph February 1, 2017 at 5:03 pm - Reply

    But you’re escaping white spaces with Regex.Escape too.
    What if I don’t want to escape it.

Leave A Comment