我尝试了一些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
。
问题是,为什么?
答案 0 :(得分:4)
捕获组不会产生匹配,而是产生匹配。您有1个匹配项和3个子匹配项,因为您有3个捕获组。至于正则表达式,您可以使用限制量词{num}
和单词边界\b
:
(\d{2})/(\d{2})/(\d{4})\b
\d{2}
表示正好匹配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