Ignore Regex C # escape sequences

I am unable to tell Regex to ignore any escape sequences.

Here is a sample code:

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

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

I just want to "?" for processing as a string.

Thanks.

EDIT: I also tried:

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

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

I also tried:

 foreach (Match m in Regex.Matches(input, "\x3f")) { ... } 
+6
source share
4 answers

.NET provides a function that automatically performs any escaping. Whenever you have some kind of input line that you want to match literally (only the characters that are there), but you know that you are using search in a regular expression, then run them using this method:

 string pattern = Regex.Escape(literalString); 

This will take care of all characters that can be metacharacters for regular expressions.

MSDN on Escape

+11
source

Do you need to avoid ? for the regex engine since ? has a definite meaning as a quantifier in regular expressions:

 \? 

You will also want to use verbatim string litals , so \ has no special meaning as an escape sequence of a C # string - these two are equivalent - @"\?" and "\\?" .

So:

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

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

+2
source

Do you need to run? in the form \\?

in regular expression, not in text.

Check out this article:

http://www.codeproject.com/Articles/371232/Escaping-in-Csharp-characters-strings-string-forma

+1
source

Use the built-in Escape method.

 Regex.Escape("/") 

See also MSDN RegEx.Escape ()

0
source

All Articles