简体   繁体   中英

regex: How to match escaped double quoted strings?

I have strings such as the following:

\"Some text inside here. And perhaps special chars including newlines...\" then more text (out here)

How do I simply match and return that which is in between the escaped double quotes, discarding the rest?

You can't use this pattern:

    \".*\"

since "dot" does not match the new-line character unless you use the flag 's' which makes the "dot" match everything (including new-line character)

and even more this pattern would mismatch this example:

    "this is a quoted text" and "this is another one"

the pattern above would match the whole string instead of the two quoted texts. (since .* is greedy and would match the longest string it can, in this case the whole string.) instead you should use .*? which makes the pattern "reluctant" and it would match the shortest string it can.

so to wrap it up you can use this pattern with flag "s" (dot-match-all):

    \".*?\"

or use this:

    \"[^"]\"

which doesn't require the "s" flag. (since [^"] matches anything but " which includes new-line.)

(I'm not familiar with PHP syntax, so you should take care of applying the flags and escaping the characters yourself.)

I'm assuming that there are only two escaped double quotes in the string

match = s.match(/\\"(.*)\\"/m)
match[1] if match

这应该适合您:

b'\\".*?\\"'

This can be done without regex too:

$str = '\"Some text inside here. And perhaps special chars including newlines...\" then more text (out here)';

$out = explode('"', $str);

echo $out[0]; // outputs "\"
echo $out[1]; // outputs "Some text... ...\"
echo $out[2]; // outputs " then...here)"

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