Javascript按空格分隔,但不是用引号分隔的 [英] Javascript split by spaces but not those in quotes

查看:21
本文介绍了Javascript按空格分隔,但不是用引号分隔的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是在空格处拆分字符串,但不拆分引号中的文本数据或将其与相邻文本分开.

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.

输入实际上是一个包含值对列表的字符串.如果 value 值包含空格,则将其括在引号中.我需要一个函数来返回一个值对元素数组,如下例所示:

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 bar" c:2'

预期结果:

a:0,b:1,moo:foo bar,c:2(长度为 4 的数组)

a:0,b:1,moo:foo bar,c:2 (An array of length 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.

任何帮助将不胜感激,克雷格

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] */

演示jsFiddle

这个正则表达式在做什么?
它在空格字符上寻找文字匹配,然后使用 Positive Lookahead 来断言下一部分可以匹配:
[w]+ = 在一次和无限次之间匹配任何单词字符 [a-zA-Z0-9_].
: = 匹配 : 字符一次(反斜杠转义).
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.

演示 Regex101(附说明)

这篇关于Javascript按空格分隔,但不是用引号分隔的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆