I was using Regex and I tried to write:
Regex RegObj2 = new Regex("\w[a][b][(c|d)][(c|d)].\w");
Gives me this error twice, one for each appearance of \w
:
unrecognized escape sequence
What am I doing wrong?
I was using Regex and I tried to write:
Regex RegObj2 = new Regex("\w[a][b][(c|d)][(c|d)].\w");
Gives me this error twice, one for each appearance of \w
:
unrecognized escape sequence
What am I doing wrong?
You are not escaping the \
s in a non-verbatim string literal.
Solution: put a @
in front of the string or double the backslashes, as per the C# rules for string literals.
Try to escape the escape ;)
Regex RegObj2 = new Regex("\\w[a][b][(c|d)][(c|d)].\\w");
or add a @ (as @Dominic Kexel suggested)
There are two levels of potential escaping required when writing a regular expression:
In this case, it's the latter which is tripping you up. Either escape the \
so that it becomes part of the string, or use a verbatim string literal (with an @
prefix) so that \
doesn't have its normal escaping meaning. So either of these:
Regex regex1 = new Regex(@"\w[a][b][(c|d)][(c|d)].\w");
Regex regex2 = new Regex("\\w[a][b][(c|d)][(c|d)].\\w");
The two approaches are absolutely equivalent at execution time. In both cases you're trying to create a string constant with the value
\w[a][b][(c|d)][(c|d)].\w
The two forms are just different ways of expressing this in C# source code.
The backslashes are not being escaped e.g. \\
or
new Regex(@"\w[a][b][(c|d)][(c|d)].\w");