Javascript按空格分隔,但不是用引号分隔 [英] Javascript split by spaces but not those in quotes
问题描述
目标是在空格处拆分字符串,但不拆分引号中的文本数据或将其与相邻文本分开。
The goal is to split a string at the spaces but not split the text data that is in quotes or separate that from the adjacent text.
输入实际上是一个包含值对列表的字符串。如果值值包含空格,则用引号括起来。我需要一个函数来返回一个值对元素数组,如下例所示:
The input is effectively a string that contains a list of value pairs. If the value value contains a space it is enclosed in quotes. I need a function that returns an array of value-pair elements as per the example below:
示例输入:
'a:0 b:1 moo:foo barc:2'
预期结果:
a:0,b:1,moo:foo bar,c:2 (长度为4的数组)
我已经检查了一大堆其他问题,但没有一个(我发现)似乎应对我的问题。大多数似乎在引号内的空格处分开,或者将'moo:'和'foo bar'分成不同的部分。
I have checked through a load of other questions but none of them (I found) seem to cope with my issue. Most seem to split at the space within the quotes or they split the 'moo:' and 'foo bar' into separate parts.
任何帮助都将非常感谢,
Craig
Any assistance would be greatly appreciated, Craig
推荐答案
您可以略微区别地使用正则表达式分隔空格后面跟单词字符和冒号(而不是不在的空格引用的部分):
You could approach it slightly differently and use a Regular Expression to split where spaces are followed by word characters and a colon (rather than a space that's not in a quoted part):
var str = 'a:0 b:1 moo:"foo bar" c:2',
arr = str.split(/ +(?=[\w]+\:)/g);
/* [a:0, b:1, moo:"foo bar", c:2] */
这个正则表达式做了什么?
它在空格字符上查找文字匹配,然后使用肯定前瞻断言下一部分可以匹配:
[\ w] +
=在一次和无限次之间匹配任何单词字符[a-zA-Z0-9_]。
\:
= match :
字符一次(反斜杠转义)。
g
=全局修饰符 - 不要'返回第一场比赛。
What's this Regex doing?
It looks for a literal match on the space character, then uses a Positive Lookahead to assert that the next part can be matched:
[\w]+
= match any word character [a-zA-Z0-9_] between one and unlimited times.
\:
= match the :
character once (backslash escaped).
g
= global modifier - don't return on first match.
这篇关于Javascript按空格分隔,但不是用引号分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!