Reputation: 45
So I'm using a Regex function on VBA to extract 5 digit numbers. What I have below is working for me so far.
It extracts 5 digit numbers such as '12345' or alphanumeric characters such as 'a12345'. However, I want it to extract 5 digit characters where we'll know what the first 2 digits are, such as 12xxx, or 45xxx.
How would I specify what the first 2 digits should be?
Function Digits(r As String) As String
Dim m
With CreateObject("vbscript.regexp")
.Pattern = "\b\d{5}\b|^(?![0-9]{6})[0-9a-zA-Z]{6}$"
.Global = False
If Not .test(r) Then Exit Function
For Each m In .Execute(r)
Multi5 = Multi5 & m & ", "
Next
Digits = Left(Digits, Len(Digits) - 2)
End With
End Function
Upvotes: 0
Views: 475
Reputation: 7567
Modify .Global = False to .Global = True
Function Digits(r As String) As String
Dim m As Object, matchs As Object
With CreateObject("vbscript.regexp")
'.Pattern = "\b\d{5}\b|^(?![0-9]{6})[0-9a-zA-Z]{6}$"
.Pattern = "12\d{3}"
.Global = True
If Not .test(r) Then Exit Function
Set matchs = .Execute(r)
For Each m In matchs
multi5 = multi5 & m & ", "
Next
Digits = Left(multi5, Len(multi5) - 2)
End With
End Function
Upvotes: 1