user2233208
user2233208

Reputation:

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|$)

Upvotes: 0

Views: 236

Answers (1)

André Nasturas
André Nasturas

Reputation: 113

"(?:"|.)*?"|^[^"]*$

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

Hope it will help you.

Upvotes: 1

Related Questions