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

Ela*_*erg 26 javascript regex split

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

我有这个字符串:

var str = 'Time:"Last 7 Days" Time:"Last 30 Days"';
Run Code Online (Sandbox Code Playgroud)

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

['Time:"Last 7 Days"', 'Time:"Last 30 Days"']
Run Code Online (Sandbox Code Playgroud)

但我的代码分为4:

['Time:', '"Last 7 Days"', 'Time:', '"Last 30 Days"']
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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

谢谢!

kch*_*kch 66

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

// -> ['Time:"Last 7 Days"', 'Time:"Last 30 Days"']
Run Code Online (Sandbox Code Playgroud)

解释:

(?:         # 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
Run Code Online (Sandbox Code Playgroud)

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

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

  • 使用单引号或双引号的 kch 模式的修改版本:`s.match(/(?:[^\s"']+|['"][^'"]*["'])+/g) ` (3认同)

Tsu*_*oka 7

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
Run Code Online (Sandbox Code Playgroud)

输出:

[ 'Time:Last 7 Days', 'Time:Last 30 Days' ]
Run Code Online (Sandbox Code Playgroud)