SplitQuoted – A split variant that deals correctly with quoted elements

' split a string, dealing correctly with quoted items'' TEXT is the string to be split' SEPARATOR is the separator char (default is comma)' QUOTES is the character used to quote strings (default is """",'  the double quote)'    you can also use a character pair (eg "{}") if the opening'    and closing quotes are different'' for example you can split the following string'     arr() = SplitQuoted("[one,two],three,[four,five]", , "[]")' into 3 items, because commas inside []' are not taken into accountFunction SplitQuoted(ByVal Text As String, Optional ByVal Separator As String = _    ",", Optional ByVal Quotes As String = """") As ArrayList    ' this is the result     Dim res As New ArrayList()    ' get the open and close chars, escape them for using in regular expressions    Dim openChar As String = System.Text.RegularExpressions.Regex.Escape _        (Quotes.Chars(0))    Dim closeChar As String = System.Text.RegularExpressions.Regex.Escape _        (Quotes.Chars(Quotes.Length - 1))    ' build the patter that searches for both quoted and unquoted elements    ' notice that the quoted element is defined by group #2     ' and the unquoted element is defined by group #3    Dim pattern As String = "s*(" & openChar & "([^" & closeChar & "]*)" & _        closeChar & "|([^" & Separator & "]+))s*"    ' search all the elements    Dim m As System.Text.RegularExpressions.Match    For Each m In System.Text.RegularExpressions.Regex.Matches(Text, pattern)        ' get a reference to the unquoted element, if it's there        Dim g3 As String = m.Groups(3).Value        If Not (g3 Is Nothing) AndAlso g3.Length > 0 Then            ' if the 3rd group is not null, then the element wasn't quoted            res.Add(g3)        Else            ' get the quoted string, but without the quotes            res.Add(m.Groups(2).Value)        End If    Next    Return resEnd Function

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: