Escape Left Bracket C# Regex
Solution 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.
Solution 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 (
Related videos on Youtube
Fraser Connor
Updated on September 17, 2022Comments
-
Fraser Connor over 1 year
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?
-
Damien_The_Unbeliever over 11 yearsSide note - you'll want to escape the
.
also, unless you want to match any character at that position.
-
-
Fraser Connor over 11 yearsDid the trick thanks very much! Also I was under the impression that standard usage of * would imply 0 or more so would get rid of any whitespace even if it didn't exist?
-
Mario over 11 yearsYes, but there's even a special character class for whitespaces:
\s
which will match any white space (space, tab, etc.).