Search code examples
excelregexvbaconditional-statementscapturing-group

Identify which capturing group was matched in the evaluated string using regex


Hallo I'm new with regular expressions and im getting a hard time figuring out how to get the group that was matched in the evaluated string using regex in VBA.

There are 4 or more different possibilities of words it can appear in the string followed by 1 or more digits:

  • W-Point =
  • WR/KE-Point=
  • WNr-Point=
  • SST_P-Nr =

One of this words appear just once in the string

Evaluated string: "3: CALL U(Base,EZSP,Nr1,Pr-nr=20,Offset=1,Path=2,WNr-Point=20,Pr=65,ON)"

Regexpattern used: (?:(W-Point=)(\d*)|(SST_P-Nr=)(\d*)|(WR/KE-Point=)(\d*)|(WNr-Point=)(\d*))

So far everything works :Example

Problem: Identify which word/digit pair was matched and get its group number. Right now im looping through the results and discarding the submatches that are empty. is there a better or efficient way to do it ?

Thanks in advance.


Solution

  • Try

    Sub test()
    
        Dim s As String
        s = "3: CALL U(Base,EZSP,Nr1,Pr-nr=20,Offset=1,Path=2,WNr-Point=20,Pr=65,ON)"
        
        Dim Regex As Object, m As Object
        Set Regex = CreateObject("vbscript.regexp")
        With Regex
          .Global = True
          .MultiLine = False
          .IgnoreCase = True
          .pattern = "(W-Point|WR/KE-Point|WNr-Point|SST_P-Nr)( *= *)(\d*)"
        End With
    
        If Regex.test(s) Then
            Set m = Regex.Execute(s)(0).submatches
            Debug.Print m(0), "'" & m(1) & "'", m(2)
        End If
    End Sub
    

    update : capture = and any spaces