cherrex cherrex - 2 months ago 30
C# Question

Regular Expression (C#) For CSV by RFC 4180

Requires universal CSV parser by specification RFC 4180.
There is the csv file, with all the problems of the specification:

Excel opens the file as it is written in the specification:

Anyone does work regex for parse it?

CSV File


"a

b

c","x

y

z",357

test;test,xxx;xxx,152

"test2,test2","xxx2,xxx2",123

"test3""test3","xxx3""xxx3",987

,qwe,13

asd,123,

,,

,123,

,,123

123,,

123,123



Expected Results

Table by EXCEL

Answer

I would say, forget about regex. CSV can be parsed easily by TextFieldParser class. To do that, you need to be

using Microsoft.VisualBasic.FileIO;

Then you can use it:

  using (TextFieldParser parser = new TextFieldParser(Stream))
  {
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");

    while (!parser.EndOfData)
    {
      string[] fields = parser.ReadFields();
      foreach (string field in fields)
      {
         // Do your stuff here ...
      }
    }
  }