1

I have a list string full of a range of different types of data. I'm reading into the list string line at a time and with each line i split it using

string[] tableNa = line.Split(',');

this gets all the different pieces of data in a line that are seperated by commas. however i have some lines like this:

47,493,'1 = EMPTY, 2 = SEND, 3 = SENDING, 4 = SENT, 5 = NOTSENT. ',0,

and i would like the split to not work within the quote marks,as i need to keep this as one piece of data. Is this possible?

loles
  • 139
  • 1
  • 1
  • 7
  • http://stackoverflow.com/questions/6209/split-a-string-ignoring-quoted-sections The replies there may be of some help to you –  Jul 20 '12 at 11:51

2 Answers2

3

Is this possible?

It's clearly possible to do this - but not with string.Split and nothing else.

If you want CSV parsing, you should find a good (possibly open source) CSV parsing library. I'm sure there are plenty around, and they're likely to be more reliable than anything you incidentally create as part of trying to provide more concrete business value.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

split a comma-separated string with both quoted and unquoted strings

Specifically, this (Regex looks terrifying, I know, but its relatively simple):

public void SplitCSV(string input)
{
    Regex csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);

    foreach (Match match in csvSplit.Matches(input))
    {
        Console.WriteLine(match.Value.TrimStart(','));
    }
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    SplitCSV("111,222,\"33,44,55\",666,\"77,88\",\"99\"");
}
Community
  • 1
  • 1