media media - 2 months ago 11
C# Question

Regex.Escape() unrecognized exception

I have the following code in


String str = @"\hello ali how are you? are you fine? hello and hi";
Console.WriteLine(Regex.Matches(Regex.Escape(str), @"\hello").Count);

when I run it, I get the following error:

{"parsing \"\hello\" - Unrecognized escape sequence \h."}

I can not understand why this happens. I need to know when a
\(some names)
happens in my code. I have used
for not using escape sequence characters but I still get the mentioned error.


Escape sequences are used independently in both Strings and regular expressions with different meanings. When you prefix the string literal with @ you are telling the compiler to interpret the string literally without escape sequences. However the Regular Expression engine again sees the "\h" and tries to interpret as an escape sequence.

Basically you need to apply both the String literal @ and the Regex.Escape function to make the \h be interpreted as a literal by both parsers:

Console.WriteLine(Regex.Matches(str, Regex.Escape(@"\hello")).Count);