Tony Bogdanov
Tony Bogdanov

Reputation: 7696

Regex: How to detect a string inside quotation marks, but include escaped quotes?

I have a really simple task, write a single regular expression, that would return a string inside quotation marks:

"this is string"

...but also include any escaped quotes:

"this is \" also a string"

Thanks in advance!

Upvotes: 0

Views: 451

Answers (1)

Dave
Dave

Reputation: 46359

First, be sure that regular expressions are what you really want. They have a habit of getting ugly.

But if you are sure, this should do the trick:

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

The outer-brackets are only so that you can fetch the content of the string without the quotes. If you don't need that, you can just use "(\\.|[^\\"])*".

To send this to PHP, you can use a string with single quotes (which does no escaping);

'"((\\.|[^\\"])*)"'

or if you must use double-quotes, escape it as needed:

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

Upvotes: 3

Related Questions