Shivam Gupta
Shivam Gupta

Reputation: 77

Regex validation for North American phone numbers

I am having trouble finding a pattern that would detect the following

909-999-9999

909 999 9999

(909) 999-9999

(909) 999 9999

999 999 9999

9999999999

\A[(]?[0-9]{3}[)]?[ ,-][0-9]{3}[ ,-][0-9]{3}\z

I tried it but it doesn't work for all the instances . I was thinking I can divide the problem by putting each character into an array and then checking it. but then the code would be too long.

Upvotes: 0

Views: 2780

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

You have 4 digits in the last group, and you specify 3 in the regex.

You also need to apply a ? quantifier (1 or 0 occurrence) to the separators since they are optional.

Use

^[(]?[0-9]{3}[)]?[ ,-]?[0-9]{3}[ ,-]?[0-9]{4}$

See the demo here

PHP demo:

$re = "/\A[(]?[0-9]{3}[)]?[ ,-]?[0-9]{3}[ ,-]?[0-9]{4}\z/"; 
$strs = array("909-999-9999", "909 999 9999", "(909) 999-9999", "(909) 999 9999", "999 999 9999","9999999999"); 
$vals = preg_grep($re, $strs);
print_r($vals);

And another one:

$re = "/\A[(]?[0-9]{3}[)]?[ ,-]?[0-9]{3}[ ,-]?[0-9]{4}\z/"; 
$str = "909-999-9999";
if (preg_match($re, $str, $m)) {
    echo "MATCHED!";
}

BTW, optional ? subpatterns perform better than alternations.

Upvotes: 3

user4227915
user4227915

Reputation:

Try this regex:

^(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}$

Explaining:

^                 # from start
(?:               # one of
    \(\d{3}\)     # '(999)' sequence
        |         # OR
    \d{3}         # '999' sequence
)                 #
[- ]?             # may exist space or hyphen
\d{3}             # three digits
[- ]?             # may exist space or hyphen
\d{4}             # four digits
$                 # end of string

Hope it helps.

Upvotes: 0

Related Questions