Pages

Wednesday 15 February 2012

Reading a CSV text file

It should be easy to read a CSV file as exported by Excel. But the quotes around any field that includes an embedded comma makes it trickier. I found this Regex nugget from an anonymous poster known only as 'h. brouwer'.
string[] SplitCsvLine(string line)
{
   return (from Match m in Regex.Matches(line,
   @"(((?<x>(?=[,\r\n] ))|""(?<x>([^""]|"""") )""|(?<x>[^,\r\n] )),?)",
   RegexOptions.ExplicitCapture)
           select m.Groups[1].Value).ToArray();
}

No comments: