Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex string definition issue

Tags:

c#

regex

I'm trying to make regex which will match all console.log("anything"); in the file. I wrote next pattern string:

@"(console\.log\(\"(.*)\"\)\;)"

The compiler doesn't compile code and says:

Method, Delegate or event is expected.

The problem is with stripslashing - " characters. But I don't know how to fix it, any ideas?

I use this pattern in method:

  js.RegexReplace(@"(console\.log\(\"(.*)\"\)\;)", "", RegexOptions.Singleline);

js is a string variable.

RegexReplace signature:

string RegexReplace(this string input, string pattern, string replacement, RegexOptions options)
like image 375
Maris Avatar asked Mar 21 '26 21:03

Maris


2 Answers

You are mixing the verbatim and the escape character. That is not working as you expect, since you can't use \ to escape ", but need to use ".

Use this string with the verbatim:

@"(console\.log\(""(.*)""\)\;)"

Use this string, without the verbatim:

"(console\\.log\\(\"(.*)\"\\)\\;)"
like image 163
Patrick Hofman Avatar answered Mar 23 '26 10:03

Patrick Hofman


Double double quotation marks:

@"(console\.log\(""(.*)""\);)"

EDIT: You do not have to escape ""s when using verbatim strings. So, the C# code will look like:

var pattern = @"(console\.log\(""(.*)""\);)";
like image 25
Wiktor Stribiżew Avatar answered Mar 23 '26 10:03

Wiktor Stribiżew