How to validate a 10-digit phone number with hyphens (e.g. 333-555-1234) using RegEx in C

1 Answer

0 votes
#include <stdio.h>
#include <regex.h>

int main() {
    const char *phone_number = "333-555-1234";
    const char *pattern = "^[0-9]{3}-[0-9]{3}-[0-9]{4}$";
    regex_t regex;

    // Compile the regular expression
    int regcomp_rv = regcomp(&regex, pattern, REG_EXTENDED);
    if (regcomp_rv) {
        fprintf(stderr, "Could not compile regex\n");
        return 1;
    }

    // Execute the regular expression
    regcomp_rv = regexec(&regex, phone_number, 0, NULL, 0);
    if (!regcomp_rv) {
        printf("Valid phone number format\n");
    } else if (regcomp_rv == REG_NOMATCH) {
        printf("Invalid phone number format\n");
    } else {
        char msgbuf[128];
        regerror(regcomp_rv, &regex, msgbuf, sizeof(msgbuf));
        fprintf(stderr, "Regex match failed: %s\n", msgbuf);
        return 1;
    }

    // Free compiled regular expression
    regfree(&regex);

    return 0;
}


  
/*
run:
  
Valid phone number format
  
*/

 



answered Feb 21, 2025 by avibootz
...