Separating a string with a comma when data can contain commas

I have a CSV file (which I did not create, and now I can’t change it and I can’t change it), containing the following lines:

"Surname, Firstname", yes, no, somestring, whatever, etc

As you can see here, the first is ,not a comma by which I want to split the line. Note that this comma is enclosed in quotation marks.

Because of this, simple string.split(',')will obviously not work, as it will provide me with an array of length 7 for the specified string instead of 6.

Is there any way around this? I was thinking about using a regex to separate a string, but I am not competent enough in regex to think of a pattern that will only be separated by commas that are not enclosed in quotation marks.

I can think of ugly, hacker ways to do this by reading every line of char on char, but this should be the last resort, as I am sure there is a better way to do this!

+5
source share
3 answers

I know that there are many people here who believe that comparisons in nature should never be used and are not very consistent with me, but I am not convinced that companies like Microsoft are not the only ones who should do this programming.

Afterall, Split does character matching, so why is it less ugly when you call existing code that doesn't exactly do exactly what you want?

, , . http://www.blackbeltcoder.com/Articles/files/reading-and-writing-csv-files-in-c.

+1

CSV - , ( ).

VisualBasic , - TextFieldParser.

+2

All Articles