用逗号分割字符串,但忽略引号内的逗号

Split string by comma, but ignore commas inside quotes

本文关键字:分割 字符串      更新时间:2023-09-26

示例字符串:

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

这里我们有4个值,用引号分隔。

当我这样做时:

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

也会分割值"Bar, baz",这是我不想要的。是否可以用正则表达式忽略引号内的逗号?

一种方法是在这里使用Positive Lookahead断言。

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"' ]