How to use Regex to match the first 28 days of the month in VB.NET

1 Answer

0 votes
Imports System
Imports System.Text.RegularExpressions

Module Module1

    Sub Main()

        '
        ' This regex matches ONLY the first 28 days of any month.
        '
        ' Explanation:
        ' ---------------------------------------------------------
        ' (0[1-9] | 1[0-9] | 2[0-8])
        '       → Matches days 01–28
        '
        ' [-\/]
        '       → Allows either "-" or "/" as the date separator
        '
        ' (0[1-9] | 1[0-2])
        '       → Matches months 01–12
        '
        ' \d{4}
        '       → Matches a 4‑digit year
        '
        ' ^ and $
        '       → Ensure the entire string is a valid date format
        '

        Dim pattern As String = "^(0[1-9]|1[0-9]|2[0-8])[-\/](0[1-9]|1[0-2])[-\/]\d{4}$"
        Dim regex As New Regex(pattern)

        Dim testDates() As String = {
            "01/01/2024",  ' valid
            "15-05-2023",  ' valid
            "28/12/2022",  ' valid
            "29/02/2024",  ' invalid (29th)
            "30/07/2024",  ' invalid
            "31/01/2024",  ' invalid
            "05/13/2024"   ' invalid month
        }

        For Each d In testDates
            Dim isMatch As Boolean = regex.IsMatch(d)
            Console.WriteLine($"{d} → {(If(isMatch, "MATCH", "NO MATCH"))}")
        Next

    End Sub

End Module



' run:
'
' 01/01/2024 → MATCH
' 15-05-2023 → MATCH
' 28/12/2022 → MATCH
' 29/02/2024 → NO MATCH
' 30/07/2024 → NO MATCH
' 31/01/2024 → NO MATCH
' 05/13/2024 → NO MATCH
'

 



answered Jun 20 by avibootz

Related questions

...