可能重複美國的電話號碼:
A comprehensive regex for phone number validation正則表達式,這將也皮卡(123)空間和123點
我這有。
1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))\s*-?\s*\d{3}\s*-?\s*\d{4}
它匹配了很多電話號碼,但它沒有抓住這兩個:少頃
(123)456-7890或123.456.7890
可能重複美國的電話號碼:
A comprehensive regex for phone number validation正則表達式,這將也皮卡(123)空間和123點
我這有。
1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))\s*-?\s*\d{3}\s*-?\s*\d{4}
它匹配了很多電話號碼,但它沒有抓住這兩個:少頃
(123)456-7890或123.456.7890
後,我問一個問題,關於a regex for a certain number of digits在一個字符串中。答案給了我這個正則表達式(\D*\d){10}{n}
。
從那時起,我已經實際使用這個用於電話號碼驗證。我不在乎他們給我一個電話號碼的格式,只要它包含10位數字。如果您只關心您獲得區號+電話號碼,那麼這也可能適用於您。
這是你的原始正則表達式的簡化版本,應該做你所要求的。
1?[\s-(.]*?\d{3}[ -).]*?\d{3}[ -.]*?\d{4}
幾個怪物
捕獲組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'
#8 => not a valid phone number: ' (123) 4565-7890'
#9 => '123' '456' '7890'
#w => not a valid phone number: '1-456-7890'
我的眼睛,他們都在流血......(不要用這樣的垃圾填充題,你'不想嘗試SEO你的問題!它看起來像垃圾郵件) – 2011-02-09 21:57:19