Error with \^ in c# regex
I have a string that contains colours in the form of "^##" where ## can be 00-99.
I wrote regex to detect and replace these colours:
Input = Regex.Replace(Input, "\^[0-9][0-9开发者_Python百科]", "");
However the compiler doesn't seem to like \^ as a means of detecting the "^" character (gives an invalid escape code error). So how do I go about looking for the ^ character in c# regex?
That happens because, well, there's no such escape sequence (\^
)
You can use:
- C# verbatim strings:
@"\^[0-9][0-9]"
- Two backslashes instead of one:
"\\^[0-9][0-9]"
Tips:
- The character class
[0-9]
is equivalent to the shorthand\d
- Instead of having
[0-9][0-9]
you could use[0-9]{2}
(or\d{2}
). This helps when you have more repetitions.
References:
Character classes, Repetition
You can try using verbatim string in Regex
Input = Regex.Replace(Input, @"\^[0-9][0-9]", "");
If you want to learn more about string literals read this article on MSDN.
Try a double-slash "\\^"
The slash is a control character in creating the string object itself.
But you want the string to contain a slash itself.
Since the C# compiler itself gives special meaning to a \
in a string, if you want a string to contain a \
you must do one of two things:
escape it by doubling it:
\\
make the string a verbatim string, by preceding the opening
"
with a@
:@"\"
- but note that this latter option changes how quotes ("
) in the string must be escaped
精彩评论