3

我有一个正则表达式模式定义为

var pattern = ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))";

我正在尝试拆分一些类似 CSV 的字符串来获取字段

一些适用于此正则表达式的示例字符串是

_input[0] = ""; // expected single blank field
_input[1] = "A,B,C"; // expected three individual fields
_input[2] = "\"A,B\",C"; // expected two fields 'A,B' and C
_input[3] = "\"ABC\"\",\"Text with,\""; // expected two fields, 'ABC"', 'Text with,'
_input[4] = "\"\",ABC\",\"next_field\""; // expected two fields, '",ABC', 'next_field'

但是,这不起作用

_input[5] = "\"\"\",ABC\",\"next_field\"";

我期待三个领域

'"', 'ABC"', 'next_field'

但我得到了两个领域

'"",ABC', 'next_field'

任何人都可以帮助这个正则表达式吗?

我认为奇怪的部分是第二列在值的开头和结尾没有引号,只是在结尾处。所以第一列的值为空,第二列是ABC"

谢谢,罗伯

4

1 回答 1

3

我认为您需要更具体地说明您的逻辑是如何处理双引号,因为您的要求似乎相互冲突。

我认为最接近您想要实现的快速版本是(请注意 1)缺少双引号转义,因为我正在使用外部工具来验证正则表达式,并且 2)我已经更改了检索方式匹配的值,请参见底部的示例):

(?<Match>(?:"[^"]*"+|[^,])*)(?:,(?<Match>(?:"[^"]*"+|[^,])*))*

它有以下逻辑:

  • 如果有双引号,则将所有内容都包含在其中,直到命中结束双引号。
  • 当到达结束双引号时,紧随其后的双引号也将包括在内。
  • 如果下一个字符不是逗号,则将其包含在内,并再次测试上述内容。
  • 如果是逗号,则结束当前匹配并在逗号后开始新的匹配。

但是,上述逻辑与您对索引 4 和 5 的期望相冲突,因为我得到:

[4] = '""' and 'ABC","next_field"'
[5] = '"""' and 'ABC","next_field"'

如果您能指出为什么上述逻辑不符合您的需求/期望,我将使用完全有效的正则表达式编辑我的答案。

要检索您的值,您可以这样做:

string pattern = @"(?<Match>(?:""[^""]*""+|[^,])*)(?:,(?<Match>(?:""[^""]*""+|[^,])*))*";

string[] testCases = new[]{
  @"",
  @"A,B,C",
  @"A,B"",C",
  @"ABC"",""Text with,",
  @""",ABC"",""next_field""",
  @""""",ABC"",""next_field"""
};

foreach(string testCase in testCases){
  var match = System.Text.RegularExpressions.Regex.Match(testCase, pattern);
  string[] matchedValues = match.Groups["Match"].Captures
    .Cast<System.Text.RegularExpressions.Capture>()
    .Select(c => c.Value)
    .ToArray();
}
于 2012-12-10T07:57:50.447 回答