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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16261635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:57:28  来源:igfitidea点击:

javascript split string by space, but ignore space in quotes (notice not to split by the colon too)

javascriptregexsplit

提问by Elad Kolberg

I need help splitting a string in javascript by space (" "), ignoring space inside quotes expression.

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

I have this string:

我有这个字符串:

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

I would expect my string to be split to 2:

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

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

but my code splits to 4:

但我的代码拆分为 4:

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

this is my code:

这是我的代码:

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

Thanks!

谢谢!

回答by kch

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

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

Explained:

解释:

(?:         # 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.

回答by Tsuneo Yoshioka

ES6 solution supporting:

ES6 解决方案支持:

  • Split by space except for inside quotes
  • Removing quotes but not for backslash escaped quotes
  • Escaped quote become quote
  • 除内引号外,按空格分割
  • 删除引号但不是用于反斜杠转义引号
  • 转义报价成为报价

Code:

代码:

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(/\(.)/,"");
        }
        return  p;
    }, {a: ['']}).a

Output:

输出:

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

回答by pady

This Works for me..

这对我有用..

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

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

Output:Array ["", "foo", " ", "bar", " ", ""sdkgyu sdkjbh zkdjv"", " ", "baz", " ", ""qux quux"", " ", "skduy", " ", ""zsk"", ""]

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