Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Regex not matching properly

Tags:

string

.net

regex

I'm trying to match quoted strings with the literal quote being accepted like:

"message\""

@"message"

with

@(["'])[\S\s]*?\1|(["'])(?:\\\2|(?!\\\2)(?!\2).)*\2

but for

"message: \"" + message + "\"

the built-in Regex in .NET matches only "message: \" instead of "message: \"" like it should according to online matchers like:

https://regexr.com/4173n

Does anyone know how to make it work properly?

.NET Code:

string pattern = "([\"'])[\\S\\s]*?\\1|([\"'])(?:\\\\\\2|(?!\\\\\\2)(?!\\2).)*\\2";
string test = "\"message: \\\"\" + message + \"\\\".\n";
MatchCollection matches = Regex.Matches(test, pattern);
like image 385
Matheus Simon Avatar asked Feb 03 '26 14:02

Matheus Simon


1 Answers

You left out a @ in the pattern and forgot to escape the literal backslash pattern, that must contain 4 backslashes in the regular string literal.

The literal string regex will look like

@(["'])[\S\s]*?\1|(["'])(?:\\\2|(?!\\\2)(?!\2).)*\2

If you want to use a regular string literal

string pattern = "@([\"'])[\\S\\s]*?\\1|([\"'])(?:\\\\\\2|(?!\\\\\\2)(?!\\2).)*\\2";

Or a verbatim string literal where you only need to escape a " with another ":

string pattern = @"@([""'])[\S\s]*?\1|([""'])(?:\\\2|(?!\\\2)(?!\2).)*\2";
like image 58
Wiktor Stribiżew Avatar answered Feb 06 '26 03:02

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!