用逗号分隔字符串但使用Javascript忽略双引号内的逗号 [英] Split a string by commas but ignore commas within double-quotes using Javascript

查看:103
本文介绍了用逗号分隔字符串但使用Javascript忽略双引号内的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找 [a,b,c,d,e,f,g,h] 变成一个包含6个元素的数组:a ,b,c,d,e,f,g,h。我是RegEx的一个菜鸟,所以任何帮助都很棒。我试图通过Javascript来做到这一点。这是我到目前为止:

I'm looking for [a, b, c, "d, e, f", g, h]to turn into an array of 6 elements: a, b, c, "d,e,f", g, h. I'm a bit of a noob with RegEx so any help is great. I'm trying to do this through Javascript. This is what I have so far:

str = str.split(/,+|"[^"]+"/g); 

但是现在它正在拆分双引号中的所有内容,这是不正确的。
感谢您的帮助。

But right now it's splitting out everything that's in the double-quotes, which is incorrect. Thanks for any help.

编辑:好的抱歉我说这个问题的确很差。我的字符串不是数组。

Okay sorry I worded this question really poorly. I'm being given a string not an array.

var str = 'a, b, c, "d, e, f", g, h';

我想用函数将那个变成一个数组。

推荐答案

这就是我要做的事。

var str = 'a, b, c, "d, e, f", g, h';
var arr = str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
/* will match:

    (
        ".*?"       double quotes + anything but double quotes + double quotes
        |           OR
        [^",\s]+    1 or more characters excl. double quotes, comma or spaces of any kind
    )
    (?=             FOLLOWED BY
        \s*,        0 or more empty spaces and a comma
        |           OR
        \s*$        0 or more empty spaces and nothing else (end of string)
    )

*/
arr = arr || [];
// this will prevent JS from throwing an error in
// the below loop when there are no matches
for (var i = 0; i < arr.length; i++) console.log('arr['+i+'] =',arr[i]);

这篇关于用逗号分隔字符串但使用Javascript忽略双引号内的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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