This code snippet will decode a CSV line and return a string array.
Imports System.Text.RegularExpressions Public Class CSV Public Shared Sub Test() Dim data() As String data = DecodeCSV("") data = DecodeCSV("1,2,3") data = DecodeCSV("1") data = DecodeCSV("1 ") data = DecodeCSV("1,""2"",3") data = DecodeCSV("1,""23"",3") data = DecodeCSV("1,""23"",3") data = DecodeCSV("12, asd, fsdfsdf, ""inquotes""") data = DecodeCSV("12,asd,""inquotes""") data = DecodeCSV("12, asd, ""inquotes""") data = DecodeCSV("12 , asd , ""inquotes""") data = DecodeCSV("12, asd, fsdfsdf, """"""Hello """"world"""" """) data = DecodeCSV("pony, and, trap") data = DecodeCSV(" yeah! ,,,,,,,,,,,man!!,,,,,,,,,, ") End Sub Public Shared Function DecodeCSV(ByVal strLine As String) As String() Dim strPattern As String Dim objMatch As Match ' build a pattern strPattern = "^" ' anchor to start of the string strPattern += "(?:""(?<value>(?:""""|[^""\f\r])*)""|(?<value>[^,\f\r""]*))" strPattern += "(?:,(?:[ \t]*""(?<value>(?:""""|[^""\f\r])*)""|(?<value>[^,\f\r""]*)))*" strPattern += "$" ' anchor to the end of the string ' get the match objMatch = Regex.Match(strLine, strPattern) ' if RegEx match was ok If objMatch.Success Then Dim objGroup As Group = objMatch.Groups("value") Dim intCount As Integer = objGroup.Captures.Count Dim arrOutput(intCount - 1) As String ' transfer data to array For i As Integer = 0 To intCount - 1 Dim objCapture As Capture = objGroup.Captures.Item(i) arrOutput(i) = objCapture.Value ' replace double-escaped quotes arrOutput(i) = arrOutput(i).Replace("""""", """") Next ' return the array Return arrOutput Else Throw New ApplicationException("Bad CSV line: " & strLine) End If End Function End Class
8 comments,
VB.Net, Tuesday, April 5, 2005 12:02


