How to split a string on multiple single‑character delimiters (and keep them) in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Module SplitKeepDelimsProgram

    Function SplitKeepDelims(s As String, delimiters As String) As List(Of String)
        Dim result As New List(Of String)()

        ' Build regex: e.g. ",;|" → "([,;|])"
        Dim pattern As String = "([" & Regex.Escape(delimiters) & "])"
        Dim re As New Regex(pattern)

        Dim lastEnd As Integer = 0

        For Each m As Match In re.Matches(s)
            ' Add text before delimiter
            If m.Index > lastEnd Then
                result.Add(s.Substring(lastEnd, m.Index - lastEnd))
            End If

            ' Add the delimiter itself
            result.Add(m.Value)

            lastEnd = m.Index + m.Length
        Next

        ' Add remaining text after last delimiter
        If lastEnd < s.Length Then
            result.Add(s.Substring(lastEnd))
        End If

        Return result
    End Function

    Sub Main()
        Dim input As String = "aa,bbb;cccc|ddddd"
        Dim parts = SplitKeepDelims(input, ",;|")

        For Each p In parts
            Console.Write("[" & p & "] ")
        Next
    End Sub

End Module



' run:
'
' [aa] [,] [bbb] [;] [cccc] [|] [ddddd] 
'

 



answered Mar 9 by avibootz

Related questions

...