我尝试了一些 Windows 日期格式,该格式依赖于区域设置。因此,为了匹配日、月和年,我开始使用正则表达式。我有一些非常基本的经验,我在Python中使用了正则表达式。
我的日期格式是dd/mm/yyyy hh:mm:ss
为了匹配日、月和年,我有以下模式:
Dim strPattern As String: strPattern = "(\d+\d+)/(\d+\d+)/(\d+\d+\d+\d+)"
我想当我的输入是:
currDate = 13/11/2014 08:36:00
然后在这段代码中:
Set allMatches = regEx.Execute(currDate)
matchesNo = allMatches.Count
If matchesNo <> 0 Then
result = allMatches.Item(0).SubMatches.Item(0)
End If
我期望这个变量matchesNo
将会有价值3
。不幸的是它有价值1
.
问题是,为什么?
捕获组不会产生匹配,而是产生子匹配。由于您有 3 个捕获组,因此您有 1 个匹配项和 3 个子匹配项。至于正则表达式,您可以使用限制量词{num}
和单词边界\b
:
(\d{2})/(\d{2})/(\d{4})\b
The \d{2}
means 精确匹配一个数字 2 次. \b
将确保整个单词匹配。
以下示例打印从包含格式的日期时间值的字符串中获取的所有日期详细信息:
Sub GetDdMmYyyyDateDetails()
Dim rExp As Object, allMatches As Object, match As Object
Dim currDate As String, day As String, month As String, year As String
currDate = "13/11/2014 08:36:00 some more 24/12/2015 01:35:55"
Set rExp = CreateObject("vbscript.regexp")
With rExp
.Global = True
.MultiLine = False
.pattern = "\b(\d{2})/(\d{2})/(\d{4})\b"
End With
Set allMatches = rExp.Execute(currDate)
For Each match In allMatches
day = match.SubMatches.Item(0)
month = match.SubMatches.Item(1)
year = match.SubMatches.Item(2)
Debug.Print "Day: " & day & vbCrLf; "Month: " & month & vbCrLf & "Year: " & year
Next
End Sub
这将打印
Day: 13
Month: 11
Year: 2014
Day: 24
Month: 12
Year: 2015
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)