【问题标题】:Split string by comma, but ignore commas inside quotes [duplicate]用逗号分割字符串,但忽略引号内的逗号[重复]
【发布时间】:2014-05-10 14:30:42
【问题描述】:

示例字符串:

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

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

当我这样做时:

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

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

【问题讨论】:

  • 您的报价是否正确平衡?引号内可以有转义引号吗? (你真的不需要 CSV 解析器吗?)
  • 当然可以用正则表达式。
  • @TimPietzcker 嗯,如果我可以通过 <script> 将其加载到我的管理页面上,我可以使用 CSV 解析器。 CSV 文件是由 PayPal 生成的,所以我假设它在语法上是有效的。
  • 你真的需要结果中的引号吗?从您的示例中,似乎逗号仅在分隔引用的短语或分隔引用的短语中的单词时出现,因此您应该能够做到 str.slice(1,-1).split('","') 如果它以这种方式保持一致。如果您要拆分的逗号周围可以有空格,那么您可以使用更简单的正则表达式.split(/"\s*,\s*"/)。如果你需要引号,那么.map(function(item) { return '"' + item + '"'; })
  • @cookiemonster 嘿,这是个好主意 :)

标签: javascript regex


【解决方案1】:

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

【讨论】:

  • 这也是我允许单引号的尝试! str.split(/,(?=(?:(?:[^'"]*(?:'|")){2})*[^'"]*$)/)如果有错误请告诉我。也需要正确!
  • @hwnd,您先生是正则表达式向导,这应该被标记为正确答案。
  • 修复了这个答案中的一些问题(例如不包括引号):stackoverflow.com/a/57121244/2771889
猜你喜欢
  • 2020-04-05
  • 1970-01-01
  • 2012-05-23
  • 2012-10-30
  • 2012-07-12
  • 1970-01-01
  • 2017-04-07
  • 2012-10-31
  • 1970-01-01
相关资源
最近更新 更多