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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <regex.h>

int is_valid_date(const char *date_str) {
    regex_t regex;
    int reti;

    // Regular expression for DD/MM/YYYY format
    const char *pattern = "^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[0-2])/([12][0-9]{3})$";

    reti = regcomp(&regex, pattern, REG_EXTENDED);
    if (reti) {
        fprintf(stderr, "Could not compile regex\n");
        return -1; // Indicate error
    }

    reti = regexec(&regex, date_str, 0, NULL, 0);
    regfree(&regex);

    if (reti == 0) {
        return 1; // Valid format
    } else if (reti == REG_NOMATCH) {
        return 0; // Invalid format
    } else {
        fprintf(stderr, "Regex match failed\n");
        return -1; // Indicate error
    }
}

int main() {
    const char *dates[] = {
        "03/05/2025",
        "31/12/2021",
        "00/01/2022",
        "15/13/2024",
        "38/07/2022",
        "1/1/2021",
        "01-01-2023",
        "2020/09/28"
    };
    int num_dates = sizeof(dates) / sizeof(dates[0]);

    for (int i = 0; i < num_dates; i++) {
        int result = is_valid_date(dates[i]);
        printf("'%s' is ", dates[i]);
        if (result == 1) {
            printf("a valid date format.\n");
        } else if (result == 0) {
            printf("an invalid date format.\n");
        } else {
            printf("had an error checking format.\n");
        }
    }

    return 0;
}



/*
run:

'03/05/2025' is a valid date format.
'31/12/2021' is a valid date format.
'00/01/2022' is an invalid date format.
'15/13/2024' is an invalid date format.
'38/07/2022' is an invalid date format.
'1/1/2021' is an invalid date format.
'01-01-2023' is an invalid date format.
'2020/09/28' is an invalid date format.

*/

 



answered May 3, 2025 by avibootz
...