Split CSV String

How would I split the next line?

test, 7535, '1,830,000', '5,000,000'

The result should be

test
7535
'1,830,000'
'5,000,000'

I'm trying to:

Dim S() as string = mystring.split(",")

But I get

test
7535
'1
830
000'
'5
000
000'

thanks

+3
source share
4 answers

Do not disassemble CSV manually if you have convenient quality libraries available . You are welcome!

CSV parsing has many potential pitfalls, and this library, according to my testing, solves most of them neatly.

However, if this is one task, and the lines are always similar to your example, you can use a regular expression, for example (VB.NET syntax may be incorrect, please correct):

        Dim s as string = "1, 2, '1,233,333', '8,444,555'";
        Dim r as Regex = new Regex(",\s");
        Dim re() as string = r.Split(s);

, . , :

  • ( , , )
+8
Dim words as New List(Of String)()
Dim inQuotes as Boolean
Dim thisWord as String
For Each c as Char in String
    If c = "'"c Then inQuotes = Not inQuotes
    If c = ","c AndAlso Not inQuotes Then
        words.Add(thisWord)
        thisWord = Nothing
    Else
        thisWord &= c
    End If
Next
+1

regexp, Split - ( Microsoft.VisualBasic.Strings) string delimeter, ",", :

    Dim s As String = "1, 2, '1,233,333', '8,444,555'"
    Dim r() As String = Split(s, ", ")
+1

RegExp: "('([^']|'')*'|[^',\r\n]*)(,|\r\n?|\n)?"

0

Source: https://habr.com/ru/post/1709905/


All Articles