#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(®ex, pattern, REG_EXTENDED);
if (regcomp_rv) {
fprintf(stderr, "Could not compile regex\n");
return 0;
}
// Execute regular expression
regcomp_rv = regexec(®ex, phone_number, 0, NULL, 0);
if (!regcomp_rv) {
regfree(®ex);
return 1;
}
else if (regcomp_rv == REG_NOMATCH) {
regfree(®ex);
return 0;
}
else {
regerror(regcomp_rv, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
regfree(®ex);
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
*/