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