0

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|$)
  • 1
    Which programming language are you trying to accomplish this in? Additionally, what should be done with e.g. `"the quick brown fox" abc "def` ? – Jan Sep 21 '17 at 20:00
  • c# - have edited the question to make it a little clearer I hope. –  Sep 21 '17 at 20:06
  • Make it lazy then: [**`^(["'])?(.*?)(?(1)\1|.+)`**](https://regex101.com/r/sf2aRi/1/) - is this what you're after? – Jan Sep 21 '17 at 20:09
  • unfortunately that allows unmatched quotes. –  Sep 21 '17 at 20:11
  • Can there be escaped quotes as well like `"abc \"foo"` – anubhava Sep 21 '17 at 20:23
  • Possible duplicate of [RegEx match quotes with 1 or more results](https://stackoverflow.com/questions/20201913/regex-match-quotes-with-1-or-more-results) – Tezra Sep 21 '17 at 21:04

1 Answers1

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

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

Hope it will help you.

  • I need to return the quoted string without the quotes. Would be great if I can make sure the last character before the closing quote is not white space and not punctuation. –  Sep 21 '17 at 20:13
  • You can use brakects to catch the text and a optional token for ending non-word characters : ```"((?:"|.)*?)\W*"```. Just get the first catch group (\1). – André Nasturas Sep 21 '17 at 20:24
  • `(?:"|.)*?"` is equivalent to `.*?"` – Will Barnwell Sep 21 '17 at 20:29
  • Also I'd say its easier to just trim the quotes off of the resulting match. Using capture groups will require a logic check to see if `\1` contains anything – Will Barnwell Sep 21 '17 at 20:32