How to split a string using a multiple character separator and maintain separator

Splitting on multiple characters is not that tricky; there are overloads on the String.Split method that does that:

Dim input As String = "##RES00012## Some value ##RES00034## Another value"
Dim parts As String() = input.Split(New String() {"##RES"}, StringSplitOptions.RemoveEmptyEntries)

This will give you an array with two elements:

"00012## Some value "
"00034## Another value"

However, the separator is left out. This is not overly tricky though; it should be prepended to each of the elements (except the first one if the string does not start with the separator):

Dim input As String = "##RES00012## Some value ##RES00034## Another value"
Dim parts As String() = input.Split(New String() {"##RES"}, StringSplitOptions.RemoveEmptyEntries)

For i As Integer = 0 To parts.Length - 1
    If i > 0 OrElse input.StartsWith("##RES") = True Then
        parts(i) = "##RES" & parts(i)
    End If
Next

Just use Microsoft.VisualBasic.Strings.Split():

Dim inputs As String = "first value##second value##third value"
Dim parts As String() = Strings.Split(inputs,"##")

Tags:

Vb.Net

String