<分区>
示例字符串:
"Foo","Bar, baz","Lorem","Ipsum"
这里我们有 4 个值,用逗号分隔在引号中。
当我这样做时:
str.split(',').forEach(…
那还会拆分我不想要的值 "Bar, baz"
。是否可以使用正则表达式忽略引号内的逗号?
标签 javascript regex
<分区>
示例字符串:
"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
或者一个Negative Lookahead
var str = '"Foo","Bar, baz","Lorem","Ipsum"',
res = str.split(/,(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/);
console.log(res); // [ '"Foo"', '"Bar, baz"', '"Lorem"', '"Ipsum"' ]
关于javascript - 用逗号分割字符串,但忽略引号内的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582276/