javascript 按空格拆分字符串,但忽略引号中的空格(注意不要也用冒号拆分) [英] javascript split string by space, but ignore space in quotes (notice not to split by the colon too)
本文介绍了javascript 按空格拆分字符串,但忽略引号中的空格(注意不要也用冒号拆分)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助将 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:
but my code splits to 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屋!
查看全文