VBA Regular Expression to Match Date

后端 未结 2 1752
栀梦
栀梦 2020-12-22 12:16

I\'m new to Regular Expressions and am having difficulty getting patterns that I find online to work in VBScript/VBA. This one is supposed to return a date found in a string

2条回答
  •  甜味超标
    2020-12-22 12:55

    It looks as if your RegEx will only find match if the whole string you pass to it is a date.

    Try removing ^ and $

    Here's your example reworked using a RegEx that will find dates in the mm/dd/yyyy and mm-dd-yyyy formats -

    Private Sub TestDate()
        MsgBox RegExDate("cancel on 12/21/2010 ")
    End Sub
    
    Private Function RegExDate(s As String) As String
        Dim re, match
        Set re = CreateObject("vbscript.regexp")
        re.Pattern = "(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}"
        re.Global = True
    
        For Each match In re.Execute(s)
            MsgBox match.Value
            RegExDate = match.Value
            Exit For
        Next
        Set re = Nothing
    End Function
    

提交回复
热议问题