匹配日期的 VBA 正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7929205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Regular Expression to Match Date
提问by HK1
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 but it fails to find any dates. What does VBScript/VBA do different than other RegEx engines that makes this fail to return a match?
我是正则表达式的新手,很难获得我在网上找到的在 VBScript/VBA 中工作的模式。这个应该返回在字符串中找到的日期,但找不到任何日期。VBScript/VBA 与其他 RegEx 引擎有何不同,导致无法返回匹配项?
Edit1
I removed the ^ and the $ from my pattern. The problem persists.
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
回答by ipr101
It looks as if your RegEx will only find match if the whole string you pass to it is a date.
看起来如果您传递给它的整个字符串是日期,您的 RegEx 只会找到匹配项。
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 -
这是您使用 RegEx 重新编写的示例,该示例将在 mm/dd/yyyy 和 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
回答by Rob Haupt
Why not use RegEx to get the portion of the string that appears to be the date and use the IsDateFunction to validate it?
为什么不使用 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
The RegEx could be cleared up a bit, but it works for your current example.
RegEx 可以稍微清理一下,但它适用于您当前的示例。