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"))
{
...
}
.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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With