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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to use Regular Expressions to match a valid date in C++

1 Answer

0 votes
#include <iostream>
#include <regex>
#include <string>

/*
^(0[1-9]|[12][0-9]|3[01]) → Matches day (01–31).
/(0[1-9]|1[0-2]) → Matches month (01–12).
/\d{4}$ → Matches year (4 digits).
*/

int main() {
    std::regex date_pattern(R"(^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[0-2])/\d{4}$)");

    // DD/MM/YYYY
    std::string date = "03/05/2025";

    if (std::regex_match(date, date_pattern)) {
        std::cout << "Valid date format!" << std::endl;
    } else {
        std::cout << "Invalid date format!" << std::endl;
    }
    
    // DD/MM/YYYY
    date = "03/14/2025";

    if (std::regex_match(date, date_pattern)) {
        std::cout << "Valid date format!" << std::endl;
    } else {
        std::cout << "Invalid date format!" << std::endl;
    }
}



/*
run:

Valid date format!
Invalid date format!

*/

 



answered May 3, 2025 by avibootz
...