问题
I have a string in the following format:
prm.Add( "blah", "blah" );
I am looking to use regex to extract the first "blah". To do this I am carving the front half off and then the back half.
The regex I'm using to get rid of "prm.Add( " is:
"prm.Add\([ ]*"
Other threads seem to indicate that escape characters before paranthesis would be acceptable. However VS complains that I have an invalid escape charcter sequence "(". If I use:
"prm.Add([ ]*"
The application errors as there is no closing paranthesis.
I realise I can get around this by using Regex.Escape on the "prm.Add(". But this isn't really very elegant.
Have I got my regex syntax wrong or does VS2010 not accept escapes of brackets?
回答1:
You just have to escape the backslash as well for the compiler to understand: "prm.Add\\([ ]*"
or @"prm.Add\([ ]*"
Otherwise the compiler couldn't understand things like "\n"
- what does the author want? A line break or the string "\n" as-is?
But I'd try to make it more dynamic, e.g. not assuming a space character being there.
回答2:
When you escape in patterns (which are strings) you have to use two escape sequences:
"prm.Add\\([ ]*"
This is because if you only use one escape, the system tries to find a character that evaluates to \(
, that doesn't exist - others that you surely know are e.g. \r
or \n
.
So, by using two \
, you actually escape the \
- leaving it in the pattern that is interpreted. And inside that pattern, you then esapce the regex-meaning of (
回答3:
The issue here is that, when escaping a string in the IDE, you are escaping something so that the compiler understands the escaping. What you want is that the REGEX object understands your string.
You need the regex object to get prm.Add\([ ]*
.
However, the backlash (\
) is a escape character, so the compiler will try to escape "(", which he doesn't knows how to. So... you need to escape the backlash itself:
prm.Add\\([ ]*
The compiler process this string and transforms \\
into \
. Which leads to what you want, since the Regex will now get a string formed by prm.Add\([ ]*
.
One way to understand this is that if you were reading the regex from a file or from a user input, only one backlash would be needed, since the compiler isn't any longer processing it (the string is acquired in run-time as opposed to compile-time in hard-coding it).
来源:https://stackoverflow.com/questions/11742854/escape-left-bracket-c-sharp-regex