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

标签 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/

相关文章:

Java (Regex) - 获取句子中的所有单词

python - 如何在 Python 2.7 中将 unicode 字符串转换为字符串文字?

javascript - 使用chance.js将随机单词放入html中

javascript - 如何将对象数组设置为格式 { x : {Number}, y : {Number} }? Javascript

javascript - 仅在用户存在时使用 Google Auth Provider 进行身份验证

c# - 如果枚举用作方法参数,是否始终需要在 C# 中进行强制转换?

javascript - React.js-具有行跨度的动态表

c# - 使用正则表达式匹配多个模式

c# - 如何编写正确的正则表达式来获取文本?

正则表达式在特定字符处停止