Waveter Waveter - 5 months ago 15
Java Question

Regex match double quote which does not follow slash character

I have string like this:


"abcd\" efg\" hi" jklm"


I want to get sub string between two first characters
"
, which is not
\"

For example, in the above string, I want to get
abcd\" efg\" hi

Currently, I replace
\"
by another character, then use the regex
"([^"]*)"
to extract the sub string between two first characters
"
. Is there any way to use regex directly without replacing
\"
by another character.

Answer

Use this regex:

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

Explanation:

[^\\]?   match an optional single character which is not backslash
"(.*?    match a quote followed by anything (non-greedy)
[^\\])"  match a quote preceded by anything other than backslash

This regex will match the least content between an opening quote and closing quote which does not have a backslash.

Regex101