仅当c#双引号外是逗号时,用逗号分隔字符串

本文关键字:字符串 分隔 仅当 | 更新日期: 2023-09-27 18:18:44

"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文件,我需要从文件中读取信息,但我需要用逗号分隔信息,因为在其他一些文件中,我可以找到逗号进入一些信息,特别是在消息,日志类型,…

 string url = @"E:'Project.csv";
 Stream stream = File.Open(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            string[] lines = null;
            using (StreamReader sr = new StreamReader(stream))
            {
                string str = sr.ReadToEnd();
                lines = Regex.Split(str, //what expression is going here);
            }

仅当c#双引号外是逗号时,用逗号分隔字符串

您可以尝试使用Lookaround

它们不检查字符串中的consume字符,而只检查match是否可能。

(?<="),(?=")

这是在线演示,并在regexstorm

进行了测试

模式解释很简单

  (?<=                     look behind to see if there is:
    "                        '"'
  )                        end of look-behind
  ,                        ','
  (?=                      look ahead to see if there is:
    "                        '"'
  )                        end of look-ahead

这只是基本的CSV解析,并且已经有一些库可以完成它。我建议你看看我以前用过的CsvHelper,而不是重新发明轮子。

您可以通过使用包管理器控制台并输入:

将它包含在您的项目中非常容易。

安装包CsvHelper

不要推出自己的CSV解析器,而是使用现有的库。在Visual Basic中有TextFieldParser类,只需在项目引用中添加Microsoft.VisualBasic的引用,然后您可以:

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();

嘿,你也可以使用这个正则表达式

var result = Regex.Split(samplestring, ",(?=(?:[^']*'[^']*')*[^']*$)");