几个怪物
捕获组 1、2、3 保存电话号码的各个部分。这是一个简单的验证。
再多一点,它就会像哥斯拉一样。
不需要区号
/^(?:\s*(?:1(?=(?:.*\d.*){10}$)\s*[.-]?\s*)?(?:\(?\s*(\d{3}|)\s*\)?\s*[.-]?))\s*(\d{3})\s*[.-]?\s*(\d{4})$/
需要区号
/^(?:\s*(?:1(?=(?:.*\d.*){10}$)\s*[.-]?\s*)?(?:\(?\s*(\d{3})\s*\)?\s*[.-]?))\s*(\d{3})\s*[.-]?\s*(\d{4})$/
代码示例(在 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__
输出
#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'
@ 987654331@
#9 => '123' '456' '7890'
#w => not a valid phone number: '1-456-7890'