简体   繁体   中英

Regex matching optional quoted string

I'm trying to match an optional quoted string of the form, odd number of quotes are invalid string.

"the quick brown fox" abc def matches the quick brown fox

and

the quick brown fox abc def

return the whole string

I found this which comes very close matching optional quotes

So I tired the following ^(")?(.*)(?(1)\\1|)

but then unmatched quotes become valid which is no good.

EDIT

If the input string starts with a " then find the closing quote and return the string in the quotes. If quotes not matched return nothing. If the string does not start with a " then return the whole string.

This comes close I think ..

^(")?([^"]+)(?(1)\1|$)

Thanks for the various comments - this does what I'm looking for

^(")?([^"]+\w)(?(1)\1|$)
"(?:"|.)*?"|^[^"]*$

First part catches quoted texts only, the second part catches entieres lines without quotes.

Hope it will help you.

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