简体   繁体   中英

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!

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM