我将如何拆分以下字符串?
test, 7535, '1,830,000', '5,000,000'
结果应该是
test
7535
'1,830,000'
'5,000,000'
我尝试:
Dim S() as string = mystring.split(",")
但我明白了,
test
7535
'1
830
000'
'5
000
000'
谢谢
当您有方便的优质库可用时,不要手动解析 CSV 。请!
CSV 解析有很多潜在的陷阱,根据我的测试,这个库可以巧妙地解决其中的大部分问题。
也就是说,如果这是一项一次性任务并且字符串总是像您的示例一样,您可以使用正则表达式,就像这样(VB.NET 语法可能是错误的,请修复):
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);
这取决于分隔逗号后始终有一个空格,并且数字之间的逗号中没有空格。如果情况并非总是如此,您可以:
如果只是为了这个例子,不需要使用正则表达式,Split函数(Microsoft.VisualBasic.Strings 的成员)可以将字符串作为分隔符,因此只需输入“,”以仅捕获后面带有空格的逗号:
Dim s As String = "1, 2, '1,233,333', '8,444,555'"
Dim r() As String = Split(s, ", ")
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
尝试使用这个正则表达式:"('([^']|'')*'|[^',\r\n]*)(,|\r\n?|\n)?"