0

I need to match strings that either quoted from the both sides or strings that do not have leading and trailing quote at all. I need to omit strings having single quote on the end - either leading or trailing quote.

Here are strings I have to match:

  • "somecharsinside"
  • somechars

I have not to match:

  • "noquotefromtheright
  • noquotefromtheleft"

I am trying something like this: ^\b.+|^\".^\"\b$

luk2302
  • 55,258
  • 23
  • 97
  • 137
nickolay
  • 3,643
  • 3
  • 32
  • 40

2 Answers2

2

The following should work:

^([^\"]*|\".*\")$

Either any non-" chars OR
" + text + "

Alternatively if you dont want to capture add ?:

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

regex101 Link

luk2302
  • 55,258
  • 23
  • 97
  • 137
  • Wow! Thanks so much for the answer! – nickolay Sep 19 '15 at 21:27
  • For me I am trying to find all the quoted words in a string. For instance, `var str = "They said \"Its okay\", \"well\" didn't they?"`, should give these two quoted words/sentences. Can you help me ? – nr5 Sep 09 '19 at 11:04
  • @nr5 you should ask a question for that. That question should include what the input is, what the output is supposed to be (and *why*) and what you have tried so far. – luk2302 Sep 09 '19 at 11:06
  • Please see if you can help: https://stackoverflow.com/questions/57852915/find-quoted-words-in-a-string-with-regex – nr5 Sep 09 '19 at 11:17
2

This task can probably be done easier without regular expression:

if ([s hasPrefix:@"\""] == [s hasSuffix:@"\""]) {
    // String matches
}

Most likely it is safe to just use == here as per documentation both methods return YES on success, not an arbitrary non-zero value. But to be on safer side you could compare BOOLs as described here

Community
  • 1
  • 1
Vladimir
  • 170,431
  • 36
  • 387
  • 313