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);
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With