Home
Manage Your Code
Snippet: Parse CSV row using Regex (C#)
Title: Parse CSV row using Regex Language: C#
Description: Returns an array of values from a CSV row handling columns in double and single quotes. This has been adapted from the example code found here : http://www.omegacoder.com/?p=60 Views: 101
Author: Paul Ward Date Added: 5/22/2008
Copy Code  
1string[] ParseCSVLine(string text)
2{
3    Regex rx = new Regex("((?([\\x27\\x22])(?:[\\x27\\x22])(?<Column>[^\\x27\\x22]*)(?:[\\x27\\x22])|(?<Column>[^,\r\n]*]*))(?:,?))+(?:$|[\r\n]{0,2})", RegexOptions.IgnorePatternWhitespace);
4
5    List<string> line = new List<string>();
6
7    foreach (Match m in rx.Matches(text))
8    {
9         if (m.Success)
10         {
11              foreach (Capture cp in m.Groups["Column"].Captures)
12              {
13                  if (string.IsNullOrEmpty(cp.Value) == false)
14                  line.Add(cp.Value);
15              }
16          }
17    }
18
19
20    return line.ToArray();
21}
Usage
Pass a row from a CSV as a string to get a string array of column values.

Remember:
	using System.Text.RegularExpressions;
	using System.Collections.Generic;
	
Notes
This has been adapted from the example code found here : http://www.omegacoder.com/?p=60