C#, regular expressions : how to parse comma-separated values, where some values might be quoted strings themselves containing commas

Try with this Regex:

"[^"\r\n]*"|'[^'\r\n]*'|[^,\r\n]*

    Regex regexObj = new Regex(@"""[^""\r\n]*""|'[^'\r\n]*'|[^,\r\n]*");
    Match matchResults = regexObj.Match(input);
    while (matchResults.Success) 
    {
        Console.WriteLine(matchResults.Value);
        matchResults = matchResults.NextMatch();
    }

Ouputs:

  • cat
  • dog
  • “0 = OFF, 1 = ON”
  • lion
  • tiger
  • ‘R = red, G = green, B = blue’
  • bear

Note: This regex solution will work for your case, however I recommend you to use a specialized library like FileHelpers.

Leave a Comment