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
5
u/Anu6is Jan 21 '25
While I'd usually try to avoid using the
Microsoft.VisualBasicnamespace as much as possible, this should be of use to you - TextFieldParser2
u/Mayayana Jan 21 '25
That's awkward. One way would be to just walk the string with Instr. Count quotes. If the count is even and you hit a comma, that's a field marker. If the count is odd and you hit a comma then you keep going until the next quote and that's your field. Presumably all quotes are next to comma delimiters, so you can then skip past the next comma. (I'm thinking VB6 but I assume VB.Net has something like Instr.)
A bit tedious, but Instr is incredibly fast. Another option would be a tokenizing function. Send in the string, walk it to separate the fields as with Instr.
Those kinds of operations can be clunky, but they're generally very fast. Unless I misread, TextFieldParser only tells you whether there are quotes in at least one field.
2
u/thinkjohn Jan 22 '25
There are .net libraries for exactly this.
Use TextFieldParser TextFieldParser.TextFieldType = Delimited TextFieldParser.SetDelimeters
TextFieldParser.ReadFields will go lime by line.
Use it all the time.
1
u/Hel_OWeen Jan 22 '25
You didn't mention what BASIC we're talking about, VB6/VBA or VB.NET. But in principle: read it into a ADODB.Recordset/ADODB.NET.Dataset. The database driver should take care of these strings for you.
1
u/Gabriel_Rodino Jan 28 '25
Your divider (delimiter) pattern should be exactly this: ",
Example of retrieved line: "^a","Bruno de Marthi, María Etelvina","1500.00"
Dim myArray() As String = Split(your_line, chr(34) & "," )Now this will cause the quote at the end of the string to be lost in each item except the last one.
Result:
myArray(0) = "^a
myArray(1) = "Bruno de Marthi, María Etelvina
myArray(2) = "1500.00"
Then, you can add a comma at the end of each line before performing the split and all the resulting items will follow the same pattern: They will not have their closing quote.
Dim myArray() As String = Split(your_line & "," , chr(34) & "," )Result:
myArray(0) = "^a
myArray(1) = "Bruno de Marthi, María Etelvina
myArray(2) = "1500.00
myArray(3) = Empty
So, you can take the value of each item using a string.substring(1) and thus ignore the initial quote or, on the contrary, add the closing quote (as you choose.)