示例字符串:
"Foo","Bar, baz","Lorem","Ipsum"
在这里,我们有用逗号分隔的引号内 4 个值。
当我执行这个操作时:
str.split(',').forEach(…
那样也会分割值"Bar, baz"
,而我不想这样。是否可能使用正则表达式忽略引号内的逗号?
示例字符串:
"Foo","Bar, baz","Lorem","Ipsum"
在这里,我们有用逗号分隔的引号内 4 个值。
当我执行这个操作时:
str.split(',').forEach(…
那样也会分割值"Bar, baz"
,而我不想这样。是否可能使用正则表达式忽略引号内的逗号?
可以使用正向先行断言来实现。
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"' ]
str.split(/,(?=(?:(?:[^'"]*(?:'|")){2})*[^'"]*$)/)
如果有错误,请告诉我。需要正确无误! - JohnnyQ
<script>
将其加载到我的管理页面上,我可以使用CSV解析器。 CSV文件是由PayPal生成的,因此我认为它在语法上是有效的。 - Šime Vidasstr.slice(1,-1).split('","')
。如果您要拆分的逗号周围可以有空格,则可以使用更简单的正则表达式.split(/"\s*,\s*"/)
。如果您需要引号,则可以使用.map(function(item) { return '"' + item + '"'; })
。 - cookie monster