Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Cannot escape quotes in a regex string

Tags:

c#

I am trying to match quotes using regex but I don't manage to escape them in the @string - I am getting an error:

output = Regex.Replace(str, @"[\d-']", string.Empty);    // valid

output = Regex.Replace(str, @"[\d-'\"]", string.Empty);  // not valid!

This one is also does not work:

string str = "[\d-'\"]" // bad compile constant value!
like image 235
Eyal Avatar asked Jul 16 '15 17:07

Eyal


2 Answers

To escape a " in an a verbatim string, use "":

Regex.Replace(str, @"[\d-'""]", string.Empty);
like image 162
DLeh Avatar answered Oct 12 '22 22:10

DLeh


The @ token suppresses \ escaping. If you remove the @ token it will work as expected, but you would have to escape the first backslash, i.e. "[\\d-'\"]"

like image 25
Steve Rukuts Avatar answered Oct 12 '22 23:10

Steve Rukuts