Regular expression to match escaped characters (quotes)

Viewed 26305

I want to build a simple regex that covers quoted strings, including any escaped quotes within them. For instance,

"This is valid"
"This is \" also \" valid"

Obviously, something like

"([^"]*)"

does not work, because it matches up to the first escaped quote.

What is the correct version?

I suppose the answer would be the same for other escaped characters (by just replacing the respective character).

By the way, I am aware of the "catch-all" regex

"(.*?)"

but I try to avoid it whenever possible, because, not surprisingly, it runs somewhat slower than a more specific one.

6 Answers

It works for me and it is simpler than current answer

(?<!\\+)"(\\"|[^"])*(?<!\\+)"

(?<!\\+) - before " not must be \, and this expression is left and right.

(\\"|[^"])* - that inside quotes: might be escaped quotes \\" or anything for except quotes [^"]

Current regexp work correctly for follow strings:

234 - false or null

"234" - true or ["234"]

"" - true or [""]

"234 + 321 \\"24\\"" - true or ["234 + 321 \\"24\\""]

"234 + 321 \\"24\\"" + 123 + "\\"test(\\"235\\")\\"" - true

or ["234 + 321 \\"24\\"", "\\"test(\\"235\\")\\""]

"234 + 321 \\"24\\"" + 123 + "\\"test(\\"235\\")\\"\\" - true

or ["234 + 321 \\"24\\""]

Related