正则expression式匹配日月和年
我尝试了一些Windowsdate格式的中继设置。 因此,为了匹配日,月和年,我开始使用正则expression式。 我有一些非常基本的经验,我在Python中使用正则expression式。
我的date格式是dd/mm/yyyy hh:mm:ss
为了匹配日,月和年,我有这样的模式:
Dim strPattern As String: strPattern = "(\d+\d+)/(\d+\d+)/(\d+\d+\d+\d+)"
我想当我的input是:
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
我期望variablesmatchesNo
将有价值3
。 不幸的是它有价值1
。
问题是,为什么?
捕获组不会产生匹配,但会产生子匹配。 你有1个匹配,3个子匹配,因为你有3个捕获组。 至于正则expression式,可以使用限制量词{num}
和单词边界\b
:
(\d{2})/(\d{2})/(\d{4})\b
\d{2}
表示精确匹配一个数字2次 。 \b
将确保整个词匹配。
这里是一个例子,打印所有的date细节信息,包含date时间值的string,格式如下:
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