用逗号分割字符串,但忽略引号内的逗号
Split string by comma, but ignore commas inside quotes
示例字符串:
"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
或负向前看
var str = '"Foo","Bar, baz","Lorem","Ipsum"',
res = str.split(/,(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/);
console.log(res); // [ '"Foo"', '"Bar, baz"', '"Lorem"', '"Ipsum"' ]
相关文章:
- 用逗号分割字符串,格式化后显示
- Javascript在多个跨度之间分割字符串
- 在Javascript中使用空格分割字符串
- 如何使用正则表达式(/^myString/g)开始分割字符串?
- 用十进制分割字符串和数字的正则表达式
- 如何基于逗号分割字符串(括号内除外)
- 用JavaScript在特殊字符处分割字符串
- 在任何换行字符处分割字符串,但如果后面没有文本则忽略
- Javascript:用逗号分割字符串,括号内除外
- 字符串分割——在第二个逗号处分割字符串
- 按不在特定边界内的字符分割字符串
- 通过多个空格分割字符串
- 如何根据被分割字符两侧的字符分割字符串
- Regex需要按"."分割字符串
- Javascript通过多个分隔符分割字符串用于逻辑表达式
- 在javascript中分割字符串不工作
- 从文本框中分割字符串
- 如何按字符的差异分割字符串作为分隔符
- 按空格分割字符串
- 使用指定的分隔符分割字符串,并替换某些部分