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

时间:2014-05-10 14:30:42

标签: javascript regex

示例字符串:

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

此处,我们在逗号分隔的引号中包含 4 值。

当我这样做时:

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

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

1 个答案:

答案 0 :(得分:39)

一种方法是在这里使用 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"' ]