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,884 questions

51,810 answers

573 users

How to validate a 10-digit standard 10 digit phone number using RegEx in C

1 Answer

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

#define MAX_PHONE_LENGTH 20

int is_valid_phone_number(const char *phone_number) {
    regex_t regex;
    char msgbuf[128];

    // regex pattern to handle all specified formats
    // 1. +91 (333) 555-1234 - country code with parentheses
    // 2. (333)-555-1234 - parentheses with hyphen
    // 3. 333-555-1234 - simple hyphen format
    // 4. 333 555 1234 - space separated
    // 5. 333.555.1234 - dot separated
    const char *pattern = 
        "^(\\+[0-9]{1,3}\\s*)?"          // Optional country code
        "(\\()?[0-9]{3}(\\))?"           // Area code with optional parentheses
        "[-. ]?"                         // Optional separator
        "[0-9]{3}"                       // Second group of digits
        "[-. ]?"                         // Optional separator
        "[0-9]{4}$";                     // Last group of digits

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

    // Execute regular expression
    regcomp_rv = regexec(&regex, phone_number, 0, NULL, 0);
    if (!regcomp_rv) {
        regfree(&regex);
        return 1;
    }
    else if (regcomp_rv == REG_NOMATCH) {
        regfree(&regex);
        return 0;
    }
    else {
        regerror(regcomp_rv, &regex, msgbuf, sizeof(msgbuf));
        fprintf(stderr, "Regex match failed: %s\n", msgbuf);
        regfree(&regex);
        return 0;
    }
}

int main() {
    char phone_numbers[][MAX_PHONE_LENGTH] = {
        "333-555-1234",
        "(333)-555-1234",
        "333 555 1234",
        "333.555.1234",
        "+91 (333) 555-1234"
    };

    int size = sizeof(phone_numbers) / sizeof(phone_numbers[0]);

    for (int i = 0; i < size; i++) {
        if (is_valid_phone_number(phone_numbers[i])) {
            printf("%s: Valid\n", phone_numbers[i]);
        } else {
            printf("%s: Invalid\n", phone_numbers[i]);
        }
    }

    return 0;
}


  
/*
run:
  
333-555-1234: Valid
(333)-555-1234: Valid
333 555 1234: Valid
333.555.1234: Valid
+91 (333) 555-1234: Valid
  
*/

 



answered Feb 22, 2025 by avibootz
edited Feb 22, 2025 by avibootz
...