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)
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)
归档时间: |
|
查看次数: |
12034 次 |
最近记录: |