我对正则表达式很陌生,很难找到在VBScript/VBA中工作的在线模式。这个应该返回一个字符串中的日期,但是它找不到任何日期。VBScript/VBA与其他无法返回匹配的RegEx引擎有什么不同?
Edit1
我从我的模式中删除了^和$。问题依然存在。
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]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))"
re.Global = True
For Each match In re.Execute(s)
MsgBox match.value
RegExDate = match.value
Exit For
Next
Set re = Nothing
End Function发布于 2011-10-28 12:27:24
看起来,您的RegEx只在传递给它的整个字符串是日期时才会找到匹配。
尝试删除^和$
下面是使用RegEx重新工作的示例,它将查找mm/dd/yyyy和格式中的日期-
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发布于 2011-10-28 12:40:55
为什么不使用RegEx来获取字符串中显示日期的部分,并使用IsDate函数来验证它呢?
Function FormatOutput(s)
Dim re, match
Set re = CreateObject("vbscript.regexp")
re.Pattern = "[\d]+[\/-][\d]+[\/-][\d]+"
re.Global = True
For Each match In re.Execute(s)
if IsDate(match.value) then
FormatOutput = CDate(match.value)
Exit For
end if
Next
Set re = Nothing
End Function可以稍微清除一下RegEx,但它适用于当前的示例。
https://stackoverflow.com/questions/7929205
复制相似问题