C# 仅当coma在双引号c之外时,才使用逗号拆分字符串#
这是我的.csv文件,我需要从文件中读取信息,但我需要用逗号分割信息,逗号在双引号之外,因为在其他一些文件中,我可以将逗号分解为一些信息,特别是在消息、日志类型中C# 仅当coma在双引号c之外时,才使用逗号拆分字符串#,c#,asp.net,regex,C#,Asp.net,Regex,这是我的.csv文件,我需要从文件中读取信息,但我需要用逗号分割信息,逗号在双引号之外,因为在其他一些文件中,我可以将逗号分解为一些信息,特别是在消息、日志类型中 "TIMESTAMP (UTC)","LOG TYPE","DEVICE TYPE","DEVICE","MESSAGE","PARAMETERS" "2014-08-12 17:30:34.437","Warning","DiverGate","141403G00294","Diver gate(s) did not connect
"TIMESTAMP (UTC)","LOG TYPE","DEVICE TYPE","DEVICE","MESSAGE","PARAMETERS"
"2014-08-12 17:30:34.437","Warning","DiverGate","141403G00294","Diver gate(s) did not connect since","2014-08-08 06:37:31 (UTC)"
"2014-08-12 17:30:34.577","Warning","DiverGate","141403G00120","Diver gate(s) did not connect since","2014-08-08 06:46:22 (UTC)"
"2014-08-13 06:45:18.890","Error","DiverGate","141403G00294","Was set to inactive, because it did not connect since","2014-08-08 06:37:31 (UTC)"
"2014-08-13 07:00:18.903","Error","DiverGate","141403G00120","Was set to inactive, because it did not connect since","2014-08-08 06:46:22 (UTC)"
这只是基本的CSV解析,已经有一些库可以完成。我建议大家看看我以前用过的,而不是试图重新发明轮子 通过使用Package Manager控制台并键入以下内容,您可以非常轻松地将其包含在项目中: 安装组件CsvHelper
这只是基本的CSV解析,已经有一些库可以完成。我建议大家看看我以前用过的,而不是试图重新发明轮子 通过使用Package Manager控制台并键入以下内容,您可以非常轻松地将其包含在项目中: 安装组件CsvHelper 你可以试试看 它们不使用字符串中的
字符,而只声明匹配是否可能
(?您可以使用
它们不使用字符串中的字符,而只声明匹配是否可能
(?使用现有库,而不是推出您自己的CSV解析器。Visual Basic提供了一个类,只需在项目引用下添加对Microsoft.VisualBasic
的引用,您就可以执行以下操作:
(?<= look behind to see if there is:
" '"'
) end of look-behind
, ','
(?= look ahead to see if there is:
" '"'
) end of look-ahead
使用现有库而不是推出自己的CSV解析器。Visual Basic提供了一个类,只需在“项目引用”下添加对Microsoft.VisualBasic的引用即可:
(?<= look behind to see if there is:
" '"'
) end of look-behind
, ','
(?= look ahead to see if there is:
" '"'
) end of look-ahead
嘿,你也可以用这个正则表达式
TextFieldParser textFieldParser = new TextFieldParser(@"E:\Project.csv");
textFieldParser.TextFieldType = FieldType.Delimited;
textFieldParser.SetDelimiters(",");
while (!textFieldParser.EndOfData)
{
string[] values = textFieldParser.ReadFields();
Console.WriteLine(string.Join("---", values));//printing the row
}
textFieldParser.Close();
嘿,你也可以用这个正则表达式
TextFieldParser textFieldParser = new TextFieldParser(@"E:\Project.csv");
textFieldParser.TextFieldType = FieldType.Delimited;
textFieldParser.SetDelimiters(",");
while (!textFieldParser.EndOfData)
{
string[] values = textFieldParser.ReadFields();
Console.WriteLine(string.Join("---", values));//printing the row
}
textFieldParser.Close();
这很好,但我还有一个问题。当它到达一行的末尾时(在本例中为4),我得到“PARAMETERS\”\r\n\“2014-08-12 17:30:34.437”“
。我无法理解\r\n\的含义,但如何\r\n\n将所有文本从\r\n\直接放入新字符串?这是我的字符串数组中的情况。每四个索引似乎都是这样这很好,但我还有一个问题。当它到达一行的末尾(在本例中为4)时,我会得到\”参数\\r\n”\“2014-08-12 17:30:34.437\”
。我不明白什么是\r\n\,但如何\r\n\n将所有文本从\r\n\直接放入新字符串?这是我的字符串数组中的情况。每四个索引都是这样
var result = Regex.Split(samplestring, ",(?=(?:[^']*'[^']*')*[^']*$)");