Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape Left Bracket C# Regex

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?

like image 964
Fraser Connor Avatar asked Dec 11 '22 23:12

Fraser Connor


1 Answers

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.

like image 104
Mario Avatar answered Dec 31 '22 04:12

Mario