PDA

View Full Version : regex function isn't working



next
06-19-2012, 09:41 AM
I can't seem to figure out why my regular expressions function isn't working. Can anyone help?
Sub t()
Debug.Print regex_match("MA-167", "[\D{2}-\d{3}]")
End Sub
Function regex_match(value As String, _
pattern As String, _
Optional multiline = False, _
Optional globl = False, _
Optional ignoreCase = False) As String

Dim re As Object, REMatches As Object

Set re = CreateObject("vbscript.regexp")

With re
.multiline = multiline
.Global = globl
.ignoreCase = ignoreCase
.pattern = pattern
End With

Set REMatches = re.Execute(value)
regex_match = REMatches(0)
End Function

error is here: Set REMatches = re.Execute(value)

Bob Phillips
06-19-2012, 11:21 AM
I think your pattern is invalid.

GTO
06-19-2012, 12:52 PM
FWIW, I would suggest testing before .Execute. That way (with a valid pattern), it doesn't hang upon no match.

Sub t()
Debug.Print regex_match("Mary had a model MA-167", "\b\D{2}-\d{3}\b")
Debug.Print regex_match("Tom had a model af-237, which is newer", "\b\D{2}-\d{3}\b")
Debug.Print regex_match("Mary also had a model XMA-167", "\b\D{2}-\d{3}\b")
'If always two letters,hyphen,three digits, maybe...
Debug.Print regex_match("Tom also had a model XX-237, which is older.", "\b[a-zA-Z]{2}-\d{3}\b")
End Sub

Function regex_match(value As String, _
pattern As String, _
Optional multiline = False, _
Optional globl = False, _
Optional ignoreCase = False) As String

Dim re As Object, REMatches As Object

Set re = CreateObject("vbscript.regexp")

With re
.multiline = multiline
.Global = globl
.ignoreCase = ignoreCase
.pattern = pattern

If .Test(value) Then
regex_match = re.Execute(value)(0)
Else
regex_match = "No Return"
End If
End With
End Function

Bob Phillips
06-19-2012, 02:56 PM
FWIW, I would suggest testing before .Execute. That way (with a valid pattern), it doesn't hang upon no match.

No, but it does with an invalid pattern :)

GTO
06-19-2012, 06:29 PM
No, but it does with an invalid pattern :)

Sorry, I meant to say that, but was less than clear:(