A couple of monsters
Capture groups 1,2,3 hold the parts of the phone number. This is a bare bones validation.
Anything more and it gets like godzilla.
Area code not required
/^(?:\s*(?:1(?=(?:.*\d.*){10}$)\s*[.-]?\s*)?(?:\(?\s*(\d{3}|)\s*\)?\s*[.-]?))\s*(\d{3})\s*[.-]?\s*(\d{4})$/
Area code required
/^(?:\s*(?:1(?=(?:.*\d.*){10}$)\s*[.-]?\s*)?(?:\(?\s*(\d{3})\s*\)?\s*[.-]?))\s*(\d{3})\s*[.-]?\s*(\d{4})$/
The code sample (in Perl)
use strict;
use warnings;
my $rxphone = qr/
^
(?: # Area code group (optional)
\s*
(?:
1 (?=(?:.*\d.*){10}$) # "1" (optional), must be 10 digits after it
\s* [.-]?\s*
)?
(?:
\(?\s* (\d{3}|) \s*\)? # Capture 1, 3 digit area code (optional)
\s* [.-]? # --- (999 is ok, so is 999)
)
) # End area code group
\s*
(\d{3}) # The rest of phone number
\s*
[.-]?
\s*
(\d{4})
$
/x;
my %phonenumbs = (
1 => '(123-456-7890',
2 => '123.456-7890',
3 => '456.7890',
4 => '4567890',
5 =>'(123) 456-7890',
6 => '1 (123) 456-7890',
7 => '11234567890',
8 => ' (123) 4565-7890',
9 => '1123.456-7890',
w => '1-456-7890',
);
for my $key ( sort keys %phonenumbs)
{
if ($phonenumbs{$key} =~ /$rxphone/) {
print "#$key => '$1' '$2' '$3'\n";
} else {
print "#$key => not a valid phone number: '$phonenumbs{$key}' \n";
}
}
__END__
Output
#1 => '123' '456' '7890'
#2 => '123' '456' '7890'
#3 => '' '456' '7890'
#4 => '' '456' '7890'
#5 => '123' '456' '7890'
#6 => '123' '456' '7890'
#7 => '123' '456' '7890'
#8 => not a valid phone number: ' (123) 4565-7890'
#9 => '123' '456' '7890'
#w => not a valid phone number: '1-456-7890'