42

In a .NET Regex pattern, what special characters need to be escaped in order to be used literally?

4 Answers 4

51

I don't know the complete set of characters - but I wouldn't rely on the knowledge anyway, and I wouldn't put it into code. Instead, I would use Regex.Escape whenever I wanted some literal text that I wasn't sure about:

// Don't actually do this to check containment... it's just a little example.
public bool RegexContains(string haystack, string needle)
{
    Regex regex = new Regex("^.*" + Regex.Escape(needle) + ".*$");
    return regex.IsMatch(haystack);
}
15
  • 1
    Escape $ character too?: var needle = @"any text here$%# more text";
    – Kiquenet
    Dec 18, 2014 at 12:50
  • 4
    @JonSkeet: thanks for pointing out Regex.Escape, I was about to re-invent a square wheel till i saw your answer.
    – mcdon
    Apr 8, 2015 at 14:05
  • 1
    @JonSkeet : I know it is late, but why not to do it to containment? I have to use .net 1.1, so I can't use String.Contains, and equivalents
    – rodrigocl
    Aug 18, 2016 at 19:21
  • 2
    @rodrigocl: use haystack.IndexOf(needle) >= 0 Sep 30, 2016 at 18:06
  • 2
    Also, interestingly, this does NOT escape "-" (hyphen), which causes issues in character classes. I guess convention is to place hyphen first in a character class so most people won't have issues like I did with what ended up being a string like this: $@"[a-zA-Z0-9{System.Text.RegularExpressions.Regex.Escape("_-$}")}]" which caused a somewhat confusing "parsing "[a-zA-Z0-9_-$]" - [x-y] range in reverse order." ArgumentException.
    – csrowell
    Jun 4, 2018 at 16:11
30

Here is the list of characters that need to be escaped to use them as normal literals:

  1. Opening square bracket [
  2. Backslash \
  3. Caret ^
  4. Dollar sign $
  5. Period or dot .
  6. Vertical bar or pipe symbol |
  7. Question mark ?
  8. Asterisk or star *
  9. Plus sign +
  10. Opening round bracket ( and the closing round bracket )
  11. Opening curly bracket {
  12. Pound/Hash sign #

These special characters are often called "metacharacters".

But, I agree with Jon to use Regex.Escape instead of hardcoding these character in code.

6
  • 6
    I think you need to include the { in your list.
    – H2ONaCl
    Dec 8, 2015 at 4:54
  • 1
    and include "
    – Arman Spr
    Jun 28, 2017 at 15:01
  • 1
    As JDB said, it depends on context. For example, ] is not on the list but needs to be escaped if used as a literal and preceded by [. Aug 2, 2019 at 19:55
  • 1
    I get an error if I try to escape asterisk or star * but seems to be working if I don't escape it.
    – Jon
    Aug 21, 2019 at 20:38
  • 1
    Why do you need to escape the octothorpe ('#') symbol? That appears to be an error in the above list.
    – knockNrod
    Dec 12, 2019 at 15:18
14

See the MSDN documentation here: http://msdn.microsoft.com/en-us/library/az24scfc.aspx#character_escapes

The problem with a complete list is that it depends on context. For example . must be escaped, unless it is enclosed in brackets, as in [.]. ] technically does not need to be escaped, unless it is preceded by [. - has no special meaning, unless it's inside of brackets, as in [A-Z]. = has no special meaning unless it is preceded by ? as in (?=).

14

I think you can get the list of chars as

List<char> chars = Enumerable.Range(0,65535)
                .Where(i=>((char)i).ToString()!=Regex.Escape(((char)i).ToString()))
                .Select(i=>(char)i)
                .ToList();

--

\t\n\f\r#$()*+.?[\^{|

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.