用逗号分隔字符串,但忽略引号内的逗号 [英] Split string by comma, but ignore commas inside quotes

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

问题描述

示例字符串:

"Foo","Bar, baz","Lorem","Ipsum"

在这里,我们用引号将 4 个值用逗号分隔.

Here we have 4 values in quotes separated by commas.

当我这样做时:

str.split(',').forEach(…

否则,该值还会拆分我不想要的值"Bar,baz" .是否可以使用正则表达式忽略引号内的逗号?

than that will also split the value "Bar, baz" which I don't want. Is it possible to ignore commas inside quotes with a regular expression?

推荐答案

一种方法是在此处使用正向超前断言.

One way would be using a Positive Lookahead assertion here.

var str = '"Foo","Bar, baz","Lorem","Ipsum"',
    res = str.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);

console.log(res);  // [ '"Foo"', '"Bar, baz"', '"Lorem"', '"Ipsum"' ]

正则表达式:

,               ','
(?=             look ahead to see if there is:
(?:             group, but do not capture (0 or more times):
(?:             group, but do not capture (2 times):
 [^"]*          any character except: '"' (0 or more times)
 "              '"'
){2}            end of grouping
)*              end of grouping
 [^"]*          any character except: '"' (0 or more times)
$               before an optional \n, and the end of the string
)               end of look-ahead

负前瞻

var str = '"Foo","Bar, baz","Lorem","Ipsum"',
    res = str.split(/,(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/);

console.log(res); // [ '"Foo"', '"Bar, baz"', '"Lorem"', '"Ipsum"' ]

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

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