Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

vb.net

Using VB.NET - I have a string:

"##RES00012##Some value ##RES00034##Another value"

That I want to split using the "##RES" as a separator to:

"##RES00012## Some value" and "##RES00034## Another value"

The string.split function doesn't seem to offer an overload to split on multiple characters or array of characters and maintain the seperator, which is required for functional purposes.

I'm looking at simply searching for indexOf("##res") and using string manipulation to do this unless I'm missing something obvious? I've searched SO for a solution but unable to find anything that actually does what I'm after.

The following is the closest i've found: how-do-i-split-a-string-by-a-multi-character-delimiter-in-c

like image 393
Tanner Avatar asked Jul 31 '09 10:07

Tanner


2 Answers

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
like image 139
Fredrik Mörk Avatar answered Nov 11 '22 23:11

Fredrik Mörk


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

Dim inputs As String = "first value##second value##third value"
Dim parts As String() = Strings.Split(inputs,"##")
like image 33
user2979918 Avatar answered Nov 11 '22 21:11

user2979918