我有一个正则表达式模式定义为
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"
谢谢, 罗布
最佳答案
我认为您需要更具体地说明您的逻辑应该如何处理双引号,因为您的要求似乎相互冲突。
我认为最接近您要实现的快速版本是这个(请注意 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();
}
关于c# - 使用正则表达式像字符串一样拆分 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13796581/