用逗号分隔字符串,但忽略引号内的逗号
问题描述:
示例字符串:
"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"' ]