C#将数据解析为CSV而不用引号中的分隔符

时间:2014-11-26 19:41:27

标签: c# regex replace

我对正则表达式模式的帮助不大..

我有这样的字符串

第一行:

250;2014-03-01;13:18:31;P25002001873;4006083016590;TCH61159500000;"Ponožky;podkolenky";441;149.00;1.000;;12740000;

第二行:

250;2014-03-01;13:18:31;P25002001873;4006083016590;TCH61159500000;"""NORDIC """ ecs;441;149.00;1.000;;12740000;

我需要通过分隔符解析这个字符串; .. 有了这个字符串我需要删除;在第一行。 (“Ponožky; Podkolenky”)但我不想删除任何其他;因为我无法解析它。

啪嗒啪嗒的意思是去除;在引号..“Ponožky; Podkolenky”=> “PonožkyPodkolenky”

3 个答案:

答案 0 :(得分:2)

您既不应该使用正则表达式,也不应该为此任务重新发明轮子。

使用微软TextFieldParser支持解析开箱即用的CSV文件:

(它根据您的需要在您引用的字段中处理;

它隐藏在Microsoft.VisualBasic - 框架内,您只需导入即可。 (将其添加为项目的参考)

using Microsoft.VisualBasic.FileIO;

//more of the class

using (TextFieldParser parser = new TextFieldParser("C:\\test\\file.csv"))
{
    parser.CommentTokens = new string[] { "#" };
    parser.SetDelimiters(new string[] { ";" });
    parser.HasFieldsEnclosedInQuotes = true;

    //skip headline if there is any
    //parser.ReadLine();

    while (!parser.EndOfData)
    {
        string[] fields = parser.ReadFields();

        foreach (String s in fields){
            MessageBox.Show(s);
        }
    }
}

连同字符串

1;2;3;"A String; with;many;;;semicolons;;;232;";5;"Another;One"

生成消息框:

1
2
3
A String; with;many;;;semicolons;;;232;
5
Another;One

答案 1 :(得分:1)

".*(;).*"

这意味着找到一个"然后是任何字符然后;和任何角色,最后关闭" 只有;在捕获组中

答案 2 :(得分:0)

我将重新提出您的问题:如果在带引号保护的字段中存在分隔符,如何分割csv字符串的字段?

第一种方式:使用csv解析器。

第二种方式:不要试图拆分每个项目,而是尝试找到它们。

string pat = @"""(?>[^""]+|"""")*""|[^;""]*";