1

我必须编写一个正则表达式来解析每个 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 也是如此。

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

任何想法?

4

1 回答 1

2

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

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);
于 2013-03-17T18:25:39.773 回答