逗号和双引号CSV格式的Regex拆分
本文关键字:Regex 拆分 格式 CSV | 更新日期: 2023-09-27 18:21:56
我在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,License
和I-Web Report,License
的结果是分开的。这是错误的。
我想用逗号把它分成数组,中间有两个不在里面的双引号。
使用真正的csv解析器,而不是使用字符串方法或regex。您可以直接使用框架中唯一可用的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的引用。
还有其他可用的:在C#中解析CSV文件,带有标题