VB.NET中按逗号分割特殊格式字符串失败问题求助
Hey there! It looks like you're stuck splitting that string because of commas inside quoted values (like those currency amounts such as "$6,411.88"). The basic Split(",") method doesn't know to ignore commas wrapped in quotes, so it's breaking your fields incorrectly. Let's fix this properly.
The Problem with Basic Splitting
Your string has fields enclosed in double quotes that contain commas—for example, "$6,411.88" gets split into two separate parts when using Split(","), which isn't what you want. We need a way to parse this like a proper CSV file, where quoted fields are treated as single units.
The Best Solution: Use TextFieldParser
VB.NET has a built-in class designed exactly for this scenario: TextFieldParser (part of the Microsoft.VisualBasic.FileIO namespace). It handles quoted fields automatically, so it won't split on commas inside quotes.
Step-by-Step Code
First, make sure to import the required namespaces:
Imports Microsoft.VisualBasic.FileIO Imports System.IO ' For StringReader
Then update your Main subroutine:
Sub Main() Dim testString As String = "1,1,PATRONAGE DISTRIBUTIONS,A00001PATR01,N/A,N/A,ZZ 1000001,1000001,7,N/A,7,S63,""$6,411.88 "",""$6,411.88 "",$0.00 ,Customer 1,,82327 330TH ST,,ELLENDALE,MN,560264012,Yes,Yes,1000001,2/15/2018,Batch 1,PAT 01,1.82E+11,75911603,""$24,761.32 "",$0.00 ,""$24,761.32 "",100%,N/A,""$3,845.08 "",$648.22 ,""$3,845.08 "",100%,N/A,""$3,062.66 "",$0.00 ,..." ' Use TextFieldParser to process the string as CSV Using parser As New TextFieldParser(New StringReader(testString)) parser.TextFieldType = FieldType.Delimited parser.SetDelimiters(",") parser.HasFieldsEnclosedInQuotes = True ' This is the key line! Try ' Read all fields from the string Dim fields As String() = parser.ReadFields() ' Loop through fields to verify (replace with your own logic) For index = 0 To fields.Length - 1 Console.WriteLine($"Field {index + 1}: {fields(index).Trim()}") Next Catch ex As MalformedLineException Console.WriteLine($"Error parsing line: {ex.Message}") End Try End Using End Sub
Why This Works
TextFieldParseris purpose-built for parsing delimited text (like CSV).- The
HasFieldsEnclosedInQuotes = Truesetting tells it to treat anything inside double quotes as a single field, even if it contains commas. - It also handles edge cases like leading/trailing spaces in fields and empty fields (the double commas in your string will become empty entries in the
fieldsarray, which is correct behavior for CSV).
Alternative: Regex (Not Recommended for Edge Cases)
If you can't use TextFieldParser, you could use a regular expression to match CSV fields. However, regex can struggle with edge cases like escaped quotes inside fields (e.g., "He said ""Hello"""), so it's not as reliable as the built-in parser. Here's a quick example if you need it:
Dim regex As New Regex(",(?=(?:[^""]*""[^""]*"")*[^""]*$)") Dim fields As String() = regex.Split(testString) ' Clean up quotes from fields manually fields = fields.Select(Function(f) f.Trim().Trim("""")).ToArray()
But again, stick with TextFieldParser for most cases—it's simpler and more robust.
内容的提问来源于stack exchange,提问作者Ananth

