I want to match strings like:
The sentence is \'He said \"Hello there\"\'
The sentence is \"He said \'Hello there\'\"
and get back a single
Very sad, but such an elegant and accurate way does not work:
(["'])(?:\\\1|[^\1]+)*\1
But we can change it a little bit, and all works fine:
(["'])((?:\\\1|(?:(?!\1)).)*)(\1)
https://regex101.com/r/dKdBMT/2
I would like to make sure that this regexp will work in all cases: please more test it.
You want to make sure the quote symbols are properly matched, so a quote starting with a single quote ends with a single quote. Also, the regex should allow for escaping a quote symbol with a backslash if it's the same symbol (double or single quote symbol) bounding the string. Try this:
"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'
These samples match this regex:
'sing"le q\'uote'
"dou\"ble 'quote"
This one seems to work:
(?:'|").*(?:'|")
or
((?:'|").*(?:'|"))
if you need a group.
Here's the demo: link
It works, because *
is a greedy quantifier, so you don't have to know what kind of quote is in the end. *
will take as much as possible.