且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript按空格分割字符串,但忽略引号中的空格(注意不要用冒号分割)

更新时间:2022-12-27 17:49:34

s = 'Time:"Last 7 Days" Time:"Last 30 Days"'
s.match(/(?:[^\s"]+|"[^"]*")+/g) 

// -> ['Time:"Last 7 Days"', 'Time:"Last 30 Days"']

说明:

(?:         # non-capturing group
  [^\s"]+   # anything that's not a space or a double-quote
  |         #   or…
  "         # opening double-quote
    [^"]*   # …followed by zero or more chacacters that are not a double-quote
  "         # …closing double-quote
)+          # each match is one or more of the things described in the group

事实证明,要修复原始表达式,您只需要添加 + 在该组:

Turns out, to fix your original expression, you just need to add a + on the group:

str.match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g)
#                         ^ here.