0

I want to detect a double quote enclosed string with a regular expression.
I did this with a simple: /"[^"]*"/
But this doesn't allow for double quotes inside the string, so I would ideally allow double quote by escaping it like \", and of course that would need also allowing \\ for a single backslash or else a string could never end in a backslash.
How can I accomplish this? ideally with a Perl-compatible regular expression.

PS: No need to escape single quotes and not possible to use them to enclose the string.

3
  • 1
    Shouldn't the original simple regexp be: /"[^"]*"/ (Otherwise you can only detect strings which contain exactly one character.)
    – Attilio
    Feb 21, 2015 at 18:52
  • @Attilio yes thanks. Any ideas on the solution?
    – Petruza
    Feb 23, 2015 at 20:48
  • 2
    @Petruza I added the [regex] tag to your question - you could have had this answered in a matter of seconds if you had that tag from the start. :) Mar 5, 2015 at 20:29

1 Answer 1

1

Here you go:

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

Demo

For each character in the string, match either a backslash followed by anything, or a character that is not a quote.

And if you need something optimized, here's an alternative:

"(?>[^\\"]++|\\.)*+"

Demo

It basically uses possessive quantifiers to avoid backtracking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.