且构网

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

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

更新时间:2023-01-14 21:18:54

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.