This question already has an answer here:
这个问题在这里已有答案:
- How to split csv whose columns may contain , 8 answers
- 如何拆分列可能包含的csv,8个答案
I am not really good in Regex.
我在Regex中并不擅长。
The string:
字符串:
"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","",""
I have done this but remove the double quotes before. But the result for string Report,License
and I-Web Report,License
are splitted. This is wrong.
我已经这样做了,但之前删除了双引号。但字符串报告,许可证和I-Web报告,许可证的结果是分开的。这是错的。
I want to split it into array by comma between double quotes not inside them.
我想用双引号之间的逗号将它拆分成数组。
1 个解决方案
#1
1
Use a real csv parser instead of using string methods or regex. You could use the TextFieldParser
which is the only one available in the framework directly:
使用真正的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);
}
}
You need to add a reference to the Microsoft.VisualBasic
dll to your project.
您需要向项目添加对Microsoft.VisualBasic dll的引用。
There are other available: Parsing CSV files in C#, with header
还有其他可用:使用标头解析C#中的CSV文件
#1
1
Use a real csv parser instead of using string methods or regex. You could use the TextFieldParser
which is the only one available in the framework directly:
使用真正的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);
}
}
You need to add a reference to the Microsoft.VisualBasic
dll to your project.
您需要向项目添加对Microsoft.VisualBasic dll的引用。
There are other available: Parsing CSV files in C#, with header
还有其他可用:使用标头解析C#中的CSV文件