Szymon Kraut
Szymon Kraut

Reputation: 3

regex extracting n-digit numbers from string

here is my code:

Dim sPartIDNumberArray() As String
Dim strIn as String

...

Dim objRegex
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
 .Global = True
 .Pattern = "(\d{7})+"
sPartIDNumberArray = .Execute(strIn)
End With

FirstPartID = sPartIDNumberArray(1)
SecondPartID = sPartIDNumberArray(2)

I need to extract two 7-digit numbers from text string like

Punktschweissen\3-Blech\1384156 RE und 1375188 ZB RE 20 PART 1

should not the .Execute method work here? I need FirstPartID = 1384156 and SecondPartID = 1375188 Thank you in advance

Upvotes: 0

Views: 871

Answers (1)

mielk
mielk

Reputation: 3940

You cannot assign the result of .Execute method to an array of strings. It returns an object of IMatchCollection2 type.

Here is the code that should work:

Sub reg()
    Dim objRegex As Object
    Dim regexMatches As Object
    Dim strIn As String
    Dim FirstPartID As String
    Dim SecondPartID As String


    strIn = "Punktschweissen\3-Blech\1384156 RE und 1375188 ZB RE 20 PART 1"


    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
        .Global = True
        .Pattern = "(\d{7})+"
        Set regexMatches = .Execute(strIn)
    End With

    FirstPartID = regexMatches(0)  'sPartIDNumberArray(1)
    SecondPartID = regexMatches(1) 'sPartIDNumberArray(2)

End Sub

Upvotes: 1

Related Questions