Regex escape questionmark and double quotes
Solution 1
?
and .
are special chars for a regex, but can't be escaped "as is" in a string litteral.
So if you put one \
, it will be wrong for a string, and if you don't put \\
, it will be taken as the "special char" of the regexp. So :
"@<a href=\"default\\.asp\\?itemID=([0-9]*)\">";
Solution 2
When using the @operator, you can regain double quotes with "".
You also need to escape certain special chars in the regex, in this case, the chars .\?
Try this:
@"<a href=""default\.asp\?itemID=([0-9]*)"">"
Solution 3
Try escaping the dot '.' character with \.
ckonig
Updated on June 05, 2022Comments
-
ckonig almost 2 years
I have data with several occurrencies of the following string:
<a href="default.asp?itemID=987">
in which the itemID is always different. I am using C# and I want to get all those itemIDs with a Regular Expression.
At first I tried this
"<a href=\"default.asp?itemID=([0-9]*)\">"
But the questionmark is a reserved character. I considered using the @ operator to disable escaping of characters. But there are still some double quotes that really need escaping. So then I would go for
"<a href=\"default.asp\\?itemID=([0-9]*)\">"
which should be translated (as a string) to
<a href="default.asp\?itemID=([0-9]*)">
But the Regex.Match method gets no success. I tried the very same regex here and it worked. What am I doing wrong?