Regular expression for dates YYYY-WW
I have the following [valid] regex expression that I am trying to add to my VBA application:
(?<year>(\d{2}){0,2}[-\/]?)(?<week>(\d{2}))
I keep getting error 5017. The 'Execute' method is not supported on the 'IRegExp2' object.
But if I pushed named captures and connected:
((\d{2}){0,2}[-\/]?)((\d{2}))
Am I assuming that the regular expression sour "vbscript" does not support named groups?
Is there another standard (for Windows) library that I can reference in VBA for a better regex parser?
I'd love to use C # one, as it worked right away and pulled my groups out, but I'm limited to VBA since the whole app plugin is in MS Office.
source to share
VBA compatible regex for YYYY-WW
(between 1900-01 and 2999-52):
([1-2][0-9])([0-9][0-9])[-\/](0[1-9]|[1-4][0-9]|5[0-2])
This excludes weeks 53 through 99.
To get century, year, week, use collection SubMatches
to get different capture groups.
Option Explicit
Sub TestYYYYWWRegex()
Dim objRegex As New RegExp
Dim objMatches As MatchCollection
Dim varTests As Variant
Dim varTest As Variant
Dim strMessage As String
objRegex.Pattern = "([1-2][0-9])([0-9][0-9])[-\/](0[1-9]|[1-4][0-9]|5[0-2])"
varTests = Array("2017-13", "1975-09", "2016-63", "zz78-0g", "1978-00", "1234-56", "1234-01", "YYYY-WW")
For Each varTest In varTests
Set objMatches = objRegex.Execute(CStr(varTest))
If objMatches.Count > 0 Then
With objMatches
strMessage = "Matched: " & CStr(varTest)
strMessage = strMessage & " C: " & .Item(0).SubMatches(0)
strMessage = strMessage & " Y: " & .Item(0).SubMatches(1)
strMessage = strMessage & " W: " & .Item(0).SubMatches(2)
End With
Else
strMessage = "No match for: " & CStr(varTest)
End If
'check test case
Debug.Print strMessage
Next varTest
End Sub
Test cases:
Matched: 2017-13 C: 20 Y: 17 W: 13
Matched: 1975-09 C: 19 Y: 75 W: 09
No match for: 2016-63
No match for: zz78-0g
No match for: 1978-00
No match for: 1234-56
Matched: 1234-01 C: 12 Y: 34 W: 01
No match for: YYYY-WW
source to share