Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to use Regex to match the first 28 days of the month in C#

1 Answer

0 votes
using System;
using System.Text.RegularExpressions;

class Program
{
    static void 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 date, not part of a longer string
        */

        string pattern = @"^(0[1-9]|1[0-9]|2[0-8])[-\/](0[1-9]|1[0-2])[-\/]\d{4}$";
        Regex regex = new Regex(pattern);

        string[] testDates =
        {
            "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
        };

        foreach (var date in testDates) {
            bool isMatch = regex.IsMatch(date);
            Console.WriteLine($"{date} → {(isMatch ? "MATCH" : "NO MATCH")}");
        }
    }
}



/*
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
...