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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23582276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:08:31  来源:igfitidea点击:

Split string by comma, but ignore commas inside quotes

javascriptregex

提问by ?ime Vidas

Example string:

示例字符串:

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

Here we have 4values in quotes separated by commas.

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

When I do this:

当我这样做时:

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

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?

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

回答by hwnd

One way would be using a Positive Lookaheadassertion here.

一种方法是在此处使用Positive Lookahead断言。

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

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

Regular expression:

正则表达式:

,               ','
(?=             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

Or a Negative Lookahead

或者一个负面的前瞻

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

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