Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore Regex escape sequences C#

Tags:

string

c#

regex

I'm having trouble telling Regex to ignore any escape sequences.

Here is some example code:

string input = "?";
foreach (Match m in Regex.Matches(input, "?"))
      {
         ...
      }

But when it is executed, it throws the following error: parsing "?" - Quantifier {x,y} following nothing.

I just want the "?" to be handled as a string.

Thanks.

EDIT: I have also tried:

foreach (Match m in Regex.Matches(input, "\?"))
                {
...
                }

Which tells me that is is not recognized as a valid escape sequence.

I've also tried:

foreach (Match m in Regex.Matches(input, "\x3f"))
                {
...
                }
like image 928
Loren Kuich Avatar asked Dec 02 '12 22:12

Loren Kuich


2 Answers

.NET provides a function that does any escaping for you automatically. Whenever you have some kind of input string, that you want to match literally (just the characters that are there), but you know you use a regex search, then run them through this method:

string pattern = Regex.Escape(literalString);

This will take care of any characters that might be meta-characters for regular expressions.

MSDN on Escape

like image 166
Martin Ender Avatar answered Oct 19 '22 13:10

Martin Ender


You need to escape the ? for the regex engine, as ? has a specific meaning as a quantifier in regular expressions:

\?

You will also want to use verbatim string literals so \ doesn't have special meaning as a C# string escape sequence - these two are equivalent - @"\?" and "\\?".

So:

string input = "?";
foreach (Match m in Regex.Matches(input, @"\?"))
{
     ...
}

In general, the backslash \ is the escape sequence within regular expressions.

like image 31
Oded Avatar answered Oct 19 '22 13:10

Oded