Search code examples
regexquotesregex-group

Regular expression matching non-empty quoted substrings


I'm looking for a regular expression that matches "batz", but not "" in this text: bla "" and "batz" foo

/"([^"]*)"/g matches both, /"([^"]+)"/g matches " and ".

Is this even possible with regular expressions?


Solution

  • You may use this regex with a captured group:

    (?:""|[^"])*("[^"]+")
    

    RegEx Demo

    RegEx Details:

    • (?:: Start a non-capture group
      • "": Match ""
      • |: OR
      • [^"]: Match any character that is not "
    • )*: Close non-capture group. * lets this group match 0 or more occurrences
    • ("[^"]+"): Match a non-empty double quoted string and capture in group #1