Marcucciboy2
Marcucciboy2

Reputation: 3259

Splitting but retaining delimiters

I've been working on a function to split a string but retain its delimiters.

Function SplitButRetainDelims(ByVal text As String, ByVal delimiters As String) As String()

    Dim Arr() As String, currentDelim As String
    Dim i As Long

    For i = 1 To Len(delimiters)
        currentDelim = Mid$(delimiters, i, 1)
        Arr = Split(Replace(text, currentDelim, currentDelim & "~"), "~")
    Next

    SplitButRetainDelims = Arr

End Function

The problem is that the way I have it now,

Arr = Split(Replace(text, currentDelim, currentDelim & "~"), "~")

will overwrite Array each time with only the split from the current delimiter. So instead of keeping the progress that previous iterations made, it resets.

I've nearly gotten to an acceptable solution before, but it was too involved to offer much benefit.

Edit: example

SplitButRetainDelims("potato (onion/soup / Green BEANS", " ()/") 
= ("potato", " ", "(", "onion", "/", "soup", " ", "/", "Green", " ", "BEANS")

Upvotes: 1

Views: 43

Answers (1)

Scott Craner
Scott Craner

Reputation: 152505

don't do the split till after all the replace:

Function SplitButRetainDelims(ByVal text As String, ByVal delimiters As String) As String()

    Dim Arr() As String, currentDelim As String
    Dim i As Long

    For i = 1 To Len(delimiters)
        currentDelim = Mid$(delimiters, i, 1)
        text = Replace(text, currentDelim, "~" & currentDelim & "~")
    Next
    text = Replace(text, "~~", "~")
    Arr = Split(text, "~")
    SplitButRetainDelims = Arr

End Function

enter image description here

Upvotes: 2

Related Questions