To achieve multi-splitting of the text based on different levels of delimiters in Visual Basic, you can modify your approach to handle each delimiter separately and recursively. The provided code snippet is a good starting point, but it needs adjustments to correctly return the expected output.
Here’s a revised version of your function that processes the string based on multiple delimiters:
Private Function MultiFinderString(BodyText As String, find As String, Optional MultiFind As String() = Nothing) As List(Of String)
Dim result As New List(Of String)()
Dim position As Integer = InStr(BodyText, find)
While position > 0
Dim startPos As Integer = position - 1
Dim endPos As Integer = position + Len(find) - 1
' Capture the substring around the found delimiter
If startPos >= 0 And endPos < BodyText.Length Then
result.Add(Mid(BodyText, startPos, endPos - startPos + 1))
End If
position = InStr(position + 1, BodyText, find)
End While
' Recursively process for the next level of delimiters
If MultiFind IsNot Nothing AndAlso MultiFind.Length > 1 Then
Dim nextLevelResults As New List(Of String)()
For Each item In result
Dim nextResults = MultiFinderString(item, MultiFind(1), MultiFind.Skip(1).ToArray())
nextLevelResults.AddRange(nextResults)
Next
Return nextLevelResults
End If
Return result
End Function
In this function:
- It searches for the specified delimiter and captures the surrounding text.
- It recursively processes the found substrings for the next level of delimiters.
- The results are collected and returned as a list of strings.
You can call this function with your initial string and the array of delimiters to get the desired output.
References: