javascript按空格分割字符串,但忽略引号中的空格(注意不要用冒号分割) [英] javascript split string by space, but ignore space in quotes (notice not to split by the colon too)
本文介绍了javascript按空格分割字符串,但忽略引号中的空格(注意不要用冒号分割)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助在空格键符号()中拆分字符串,忽略引号表达式中的空格。
I need help splitting a string in javascript by space (" "), ignoring space inside quotes expression.
我有这个字符串:
var str = 'Time:"Last 7 Days" Time:"Last 30 Days"';
我希望我的字符串被拆分为2:
I would expect my string to be split to 2:
['Time:"Last 7 Days"', 'Time:"Last 30 Days"']
但我的代码拆分为4:
['Time:', '"Last 7 Days"', 'Time:', '"Last 30 Days"']
这是我的代码:
str.match(/(".*?"|[^"\s]+)(?=\s*|\s*$)/g);
谢谢!
推荐答案
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
事实证明,要修复原始表达式,您只需要添加 +
在该组:
Turns out, to fix your original expression, you just need to add a +
on the group:
str.match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g)
# ^ here.
这篇关于javascript按空格分割字符串,但忽略引号中的空格(注意不要用冒号分割)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文