41

我需要帮助按空格(“”)在 javascript 中拆分字符串,忽略引号表达式中的空格。

我有这个字符串:

var str = 'Time:"Last 7 Days" Time:"Last 30 Days"';

我希望我的字符串被拆分为 2:

['Time:"Last 7 Days"', 'Time:"Last 30 Days"']

但我的代码拆分为 4:

['Time:', '"Last 7 Days"', 'Time:', '"Last 30 Days"']

这是我的代码:

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

谢谢!

4

3 回答 3

85
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

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

str.match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g)
#                         ^ here.
于 2013-04-28T09:56:29.077 回答
4

ES6 解决方案支持:

  • 除内引号外按空格分隔
  • 删除引号但不删除反斜杠转义引号
  • 转义报价变成报价

代码:

str.match(/\\?.|^$/g).reduce((p, c) => {
        if(c === '"'){
            p.quote ^= 1;
        }else if(!p.quote && c === ' '){
            p.a.push('');
        }else{
            p.a[p.a.length-1] += c.replace(/\\(.)/,"$1");
        }
        return  p;
    }, {a: ['']}).a

输出:

[ 'Time:Last 7 Days', 'Time:Last 30 Days' ]
于 2017-10-26T05:33:14.093 回答
0

这对我有用..

var myString = 'foo bar "sdkgyu sdkjbh zkdjv" baz "qux quux" skduy "zsk"'; console.log(myString.split(/([^\s"]+|"[^"]*")+/g));

输出: 数组 ["", "foo", " ", "bar", " ", ""sdkgyu sdkjbh zkdjv"", " ", "baz", " ", ""qux quux"", " ", " skduy"、""、""zsk""、""]

于 2020-04-21T06:39:33.800 回答