我该如何分割以下字符串?
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)?"