C# 读取CSV文件

CSV文件是用逗号作为分隔符的,所以如果是简单的CSV文件,用split(',')就可以了。

但是Excel 编辑CSV文件,且内容中有逗号,得到的csv文件如下:

"aaa,aaa",bbb,ccc

这时候split(',')就行不通了。

为了对应这种情况,写了一段简单的代码处理一下。

var result = new List<string>();
var filter = @"([^\""\,]*[^\""\,])|[\""]([^\""]*)[\""]";
Match match = Regex.Match(line, filter, RegexOptions.IgnoreCase);

while (match.Success)
{
    if (!string.IsNullOrEmpty(match.Groups[2].Value))
    {
        result.Add(match.Groups[2].Value);
    }
    else 
    {
        result.Add(match.Value);
    }
    match = match.NextMatch();
}

核心代码就是上面的正则表达式,它可以区分有双引号的部分和非双引号分割的部分。

([^\""\,]*[^\""\,])  不以双引号及逗号做开头和结果的字符串
[\""]([^\""]*)[\""]  以双引号及逗号做开头和结果的字符串