Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading \" inside "..." as string token

Tags:

c#

regex

I'm using C# regular expressions for my project in compiler design.

I'm working with a lexical analyzer and I have to tokenize the code depending on the rules I have set.

I defined my string as [\".*?\"] and double quote as [\"].

When I input "Hi" it is read as STRING TOKEN.

But when I input " \" ", it yields STRING for " \" and DOUBLE-QUOTE for ".

I want it to be read as STRING TOKEN.

In other words, I want to correctly parse strings containing escaped double quotes.

like image 260
Jason Delgado Avatar asked Jul 31 '26 14:07

Jason Delgado


1 Answers

I believe the pattern you want is:

"(?:[^"]|\")*"

This will match any non-quote character or slash-quote pair inside quotes. For example:

var input = @"1 2 3 ""Hello \""Word\""!""";
var match = Regex.Match(input, @"""(?:[^""]|\"")*""");

Console.WriteLine(match.Value); // "Hello \"Word\"!"
like image 90
p.s.w.g Avatar answered Aug 03 '26 04:08

p.s.w.g



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!