【问题标题】:Regex expression to match even number of double quotation (") not match single one for CSV正则表达式匹配偶数个双引号 (") 不匹配 CSV 单引号
【发布时间】:2013-03-17 18:09:46
【问题描述】:

我必须编写一个正则表达式来解析每个 CSV 行。例如,正则表达式是匹配包含偶数个双引号(")的双引号字符串,而不是单引号。

例如,CSV 分隔符是制表符,\t。我有这样一行:

"first column ""end"\tsecond column\t"third \nNewLine\rcolumn\tend"

正则表达式将允许我提取如下三列:

first column ""end
second column
third \nNewLine\rcolumn\tend

请注意,第一列有两个双引号,但它可以允许偶数个双引号。

请注意,第三列中有\t,\n和\r也是。

如果便于编写正则表达式,可以引用第一列和第三列。

有什么想法吗?

【问题讨论】:

  • 我试过了,但我不知道如何处理带引号的字符串中有偶数个双引号的情况。

标签: c# regex


【解决方案1】:

当且仅当有偶数个引号时,如何在标签上拆分?

splitArray = Regex.Split(subject, 
    @"\t        # Match a tab
    (?=         # if the following regex matches after it:
     (?:        # Match...
      [^""]*""  # Any number of non-quotes, followed by a quote
      [^""]*""  # ditto, to ensure an even number of quotes
     )*         # Repeat as many times as needed
     [^""]*     # Then match any remaining non-quote characters
     $          # until the end of the string.
    )           # End of lookahead assertion", 
    RegexOptions.IgnorePatternWhitespace);

【讨论】:

  • @Tim Pietzcker 你如何达到你的正则表达式水平。能推荐一下学习方法和学习资料吗?
  • @Pingpong:我从使用RegexBuddy 及其教程以及阅读Friedl 的“掌握正则表达式”中学到的最多。
猜你喜欢
  • 1970-01-01
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 2012-03-24
  • 1970-01-01
  • 2018-06-15
相关资源
最近更新 更多