简体   繁体   English

正则表达式以匹配日月和年

[英]Regex to match day month and year

I'm tried a bit with Windows date format which relays on regional settings. 我尝试了Windows日期格式,该格式可在区域设置上进行中继。 Therefore to match day, month and year I started to use regex. 因此,为了匹配日,月和年,我开始使用正则表达式。 I have some very basic experience in it, I used regex in Python. 我有一些非常基本的经验,我在Python中使用了regex。

My date format is dd/mm/yyyy hh:mm:ss 我的日期格式是dd/mm/yyyy hh:mm:ss

To match day, month and year I have this pattern: 为了匹配日,月和年,我有以下模式:

Dim strPattern As String: strPattern = "(\d+\d+)/(\d+\d+)/(\d+\d+\d+\d+)"

and I suppose that when my input is: 我想当我的输入是:

currDate = 13/11/2014 08:36:00

then in this code: 然后在这段代码中:

Set allMatches = regEx.Execute(currDate)
matchesNo = allMatches.Count
If matchesNo <> 0 Then
    result = allMatches.Item(0).SubMatches.Item(0)
End If

I would expect that variable matchesNo will have value 3 . 我希望变量matchesNo值为3 Unfortunately it has value 1 . 不幸的是它具有价值1

Question is, why? 问题是,为什么?

Capturing groups do not yield matches, but submatches. 捕获组不会产生匹配项,而是子匹配项。 You have 1 match, and 3 submatches since you have 3 capturing groups. 由于您有3个捕获组,因此您有1个匹配项和3个子匹配项。 And as for the regex, you may use limiting quantifier {num} , and word boundaries \\b : 对于正则表达式,您可以使用限制量词{num}和单词边界\\b

(\d{2})/(\d{2})/(\d{4})\b

The \\d{2} means match a digit exactly 2 times . \\d{2}表示精确匹配2个数字 \\b will ensure a whole word match. \\b将确保整个单词匹配。

Here is an example that prints all the date details obtained from the strings containing datetime values in your format: 下面是一个示例,该示例以您的格式打印从包含datetime值的字符串获得的所有日期详细信息:

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

This will print 这将打印

Day: 13
Month: 11
Year: 2014
Day: 24
Month: 12
Year: 2015

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM