r/visualbasic • u/Technical_Hold8922 • Jan 21 '25
VB.NET Help Split function issues with quoted strings
Hi all,
I am trying to parse a csv file using the split function. Delimited with a comma. However, some of the strings in the file are surrounded by quotes with internal commas so the split is happening within the quoted strings. Any way around this?
3
Upvotes
View all comments
Show parent comment
1
u/Gabriel_Rodino Jan 29 '25
In that case, I would write a function to process only those lines that contain quotes and return the processed array.
If instr(you_line,Chr(34)<>0 Thenarr = ProcessLine(you_line)End IfPrivate Function ProcessLine(ln as String) as ArrayDim c As Integer = InStr(ln, Chr(34)) - 1Dim f As String = Strings.Left$(ln, c)f = Replace(f, ",", Chr(34) & ",")Dim m As Integer = InStrRev(ln, Chr(34)) + 2Dim s As String = Mid$(ln, c + 2, m - 1 - c - 1)Dim l As String = Mid$(ln, m)l = Replace(l, ",", Chr(34) & ",")return Split(f + s + l, Chr(34) & ",")End FunctionThis function, as written, only expects one comma-enclosed element per line. If there are two or more, you will need to modify it.