正则表达式分为逗号和双引号CSV格式

时间:2015-11-13 10:44:20

标签: c# regex csv

我在Regex中并不擅长。

字符串:

"FF","asdadasd60","Report,License","502","5A1301","I-Web Report,License","50A1","PR02","02","5A11","REL","","","","A1170600","500008","FA10","5000001","","","","","000000000.000","","000000000.000","","000000000.000","","000000000.000","","00000000","00000000","",""

我已经这样做了,但之前删除了双引号。但字符串Report,LicenseI-Web Report,License的结果是分开的。这是错误的。

我想用双引号之间的逗号将它分成数组。

1 个答案:

答案 0 :(得分:1)

使用真正的csv解析器而不是使用字符串方法或正则表达式。您可以直接使用框架中唯一可用的TextFieldParser

var allLineFields = new List<string[]>();
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(new StringReader(str)))
{
    parser.Delimiters = new string[] { "," };
    parser.HasFieldsEnclosedInQuotes = true; // <--- !!!
    string[] lineFields;
    while ((lineFields = parser.ReadFields()) != null)
    {
        allLineFields.Add(lineFields);
    }
}

您需要在项目中添加对Microsoft.VisualBasic dll的引用。

还有其他可用的内容:Parsing CSV files in C#, with header