我需要帮助在空格(“”)的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);
谢谢!
答案 0 :(得分:59)
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.
答案 1 :(得分:1)
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' ]
答案 2 :(得分:-1)
这对我有用。
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”“ ,“”,“” zsk“”,“”]