【问题标题】:Capturing null values in comma-delimited CSV using Regex使用正则表达式在逗号分隔的 CSV 中捕获空值
【发布时间】:2014-03-17 16:26:32
【问题描述】:

我有一个尝试使用正则表达式解析的 CSV 文件。文件通过分隔符、回车等方式进行控制。

我有以下将每一行拆分为一个值数组。

/('[^']+'|[^,]+)/g

我正在尝试解决此模式的 2 个问题。首先是它打破了答案中使用的逗号。

我要解决的第二个主要问题是如何更改此模式以允许空值仍反映在输出数组中。

测试输入

,,,'This is a test', 'I'm a test as well', 'I,too, am a test'

期望的输出

null
null
null
This is a test
I'm a test as well
I,too, am a test

目前我正在接受

This is a test
I'm a test as well
I
too
am a test

【问题讨论】:

  • 您使用哪种语言?
  • 目前 - 用于原型设计的 JavaScript/Nodejs。项目的模式和整体逻辑最终可以移植到 C# 中。
  • 主要问题是字符串中的文字引号没有被转义。
  • 怀疑这是否可以通过纯正则表达式实现,尤其是由于嵌套的逗号和单引号,无法使用后向 (JS)。您应该尝试通过编写各种迷你解析器以编程方式执行此操作。
  • 您可能会发现我对类似问题的回答会有所帮助:How can I parse a CSV string with Javascript?

标签: regex csv


【解决方案1】:

这将完全匹配您希望它也匹配的内容

(?:,|^)    # start with start of line or comma
(\s*       # start capture group
 (?:
  [^',].*? # match anything not starting with a comma or a quote
  |        # OR 
  '.*?'\s* # match anything starting and ending with quotes
 )?        # OR nothing at all 
)
(?=,|$)    # end with , or end of string, but don't match

see it in action

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多