regex - Splitting the line in a CSV using C#


Keywords:c# 


Question: 

I am reading a CSV file and a line reads like this

Context Tenant: {Vendor: 1, Customer: 719046046}","1,664,705.67","","7/11/2017 4:55 PM"

Now i would like to split this and collect each values in a Array.

value[0] should be Context Tenant: {Vendor: 1, Customer: 719046046}
value[1] should be 1,664,705.67
value[2] should be 7/11/2017 4:55 PM.

Tried using Regex and Split

var values = line1.Split(new char[] { '\\', '"' ,','}, StringSplitOptions.RemoveEmptyEntries);

var values = Regex.Split(line1, "\\,");

However i am unable to read the value as i expected. Can you please share some light.


2 Answers: 

this should do the job. This version will remove the empty spaces

string [] n_new = g.Split(new string[] { "\",\""}, StringSplitOptions.RemoveEmptyEntries)

To get rid of the starting end end " you can put an additional Trim before the Split:

string [] ret = g.Trim('"').Split(new string[] { "\",\""}, StringSplitOptions.RemoveEmptyEntries);
 

Because some of your elements contains commas I'd suggest splitting specifically on ",", so use this in your split statement: "\",\"". So you should end up with:

var values = Regex.Split(line1, "\",\"");

And then to solve your issues of including " in the results, consider:

foreach (string value in string[] values)
    value = value.Replace("\"\"", "");

to get rid of all the unwanted extra double quotes ("). Sort of hacky but it should do the trick.