0

I have a csv file, when i use the split function, my issue is that the 16th segment of the array has a name in it (in most cases) that has first and last name split by a comma. This obviously causes me issues as it puts my array out of sync. any suggestions on how i can handle this?

the string in the 16th segment is surrounded by "" if that helps, the split function still splits it though.

Barry
  • 63
  • 7
  • http://stackoverflow.com/questions/11456850/split-a-string-by-commas-but-ignore-commas-within-double-quotes-using-javascript – Paul Michaels Dec 24 '13 at 12:01

4 Answers4

2

you can use TextFieldParser as indicated here

Community
  • 1
  • 1
rt2800
  • 3,045
  • 2
  • 19
  • 26
  • i am not sure this will help me, i am not loloking for a whole new method of parsing the text file, just how to handle the use of a comma inside a "field". – Barry Dec 24 '13 at 12:16
  • http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1 – Barry Dec 24 '13 at 12:17
  • looking at the link above would this also split the comma's within the ""? – Barry Dec 24 '13 at 12:24
  • you can set TextFieldParser.HasFieldsEnclosedInQuotes=true to escape comma inside quoted field – rt2800 Dec 24 '13 at 12:41
0

I recommend Lumen CSV Library, it can correctly handle field values with commas. Also it has a very good performance, and a very simple usage. See the link above, it won't disappoint you.

WAKU
  • 290
  • 3
  • 17
0

I think you're missing the point. Split is only good for simple csv parsing. Anything that gets even a little complicated means a lot of extra code. Something like the TextFieldParser is better suited to what you want. However if you must use Split here's one way:

    Dim TempArray() As String
    Dim Output As New List(Of String)
    If SourceString.Contains("""") Then
        TempArray = SourceString.Split(""""c)
        Output.AddRange(TempArray(0).Split(","c))
        Output.Add(TempArray(1))
        'If the quoted part of the csv line is at the end of the line omit this statement.
        Output.AddRange(TempArray(2).Split(","c))
    Else
        Output = New List(Of String)(SourceString.Split(","c))
    End If

This assumes that the data is strictly organized, except for the quotes, if not you'll have to add validation code.

tinstaafl
  • 6,908
  • 2
  • 15
  • 22
0

Split by "," with the quotes instead of just a comma. Don't forget to take care of the first and last quotes on the line.

roundar
  • 1,593
  • 1
  • 18
  • 22