Kokno
Kokno

Reputation: 335

Split string using pattern VBA regex

Although there is already lots of regex topic, I couldn't find a good solution to split a string like this: 12ABC34DE102/103/104FG

Result should be: 12ABC34DE102FG | 12ABC34DE103FG | 12ABC34DE104FG

EDIT: Other example: 12ABC34DE102/103AH001/AH002 should be 12ABC34DE102AH001 | 12ABC34DE103AH001 | 12ABC34DE102AH002 | 12ABC34DE103AH002

With this regex: ([0-9]{2,3})*\/([0-9]{2,3})*, I'm able to get into groups the changing values but I cannot go further.

Thank you

Upvotes: 0

Views: 169

Answers (1)

JvdV
JvdV

Reputation: 75840

I feel like you may want to first capture the forward slash delimited substring and then use Split() to create an array to go over. Something like so:

Sub Test()

Dim str As String: str = "12ABC34DE102/103/104FG"
Dim arr() As String, x As Long

With CreateObject("vbscript.regexp")
    .Pattern = "\d{2,3}(?:/\d{2,3})+"
    If .Test(str) Then
        arr = Split(.Execute(str)(0), "/")
        For x = LBound(arr) To UBound(arr)
            arr(x) = .Replace(str, arr(x))
        Next
    End If
End With

End Sub

Running this will end up with:

enter image description here

Upvotes: 2

Related Questions