Search code examples
javascriptregexregex-group

Regex pattern for extraction of double-quoted and non-quoted strings Javascript


im desperately trying to extract double quoted and non-quoted words from following string (Please note the single quotes around):

'"Cloud Technology" Foundation "Board"'

Desired groups are:

  1. "Cloud Technology"
  2. Foundation
  3. "Board"

I came up with this pattern (?:\"(.*?)\")|(?:\s(\S*?)\s) have a look in regex101.com

But the pattern doesnt works if the string would be for example '"Cloud Technology" Foundation'


Solution

  • You can use

    console.log(`'"Cloud Technology" Foundation "Board"'`.match(/"[^"]+"|[^\s']+/g))

    See the regex demo. Details:

    • "[^"]+" - ", zero or more chars other than " and then a " char
    • | - or
    • [^\s']+ - one or more chars other than whitespace and ' chars.