[英]Regex for phone # country code with area code
我需要一個正則表達式來匹配此國家代碼+地區代碼電話#格式:
1-201
前兩個字符始終為1-
,后三個字符始終為201
到989
之間的數字。
我目前有([1][\\-][0-9]{3})
來指定1-xyz
和限制長度,但是我怎么能有最后一組來限制這些范圍呢?
這將在PHP中使用。
使用此正則表達式:
^1\-(2\d[1-9])|([3-8]\d{2})|(9[0-8]\d)$
這是對三個捕獲組/范圍的說明:
(2\\d[1-9])
匹配201
至299
([3-8]\\d{2})
匹配300
到899
(9[0-8]\\d)
匹配900
到989
這是一個可以測試此正則表達式的鏈接:
更新:
顯然,Laravel不喜歡擁有這么多嵌套的捕獲組,但是這種簡化應該可以滿足您的需求:
1-(2\d[1-9]|[3-8]\d{2}|9[0-8]\d)
我不會為此使用正則表達式。 它將變得凌亂並且難以維護。
我會做這樣的事情:
$strings = array('1-201', '1-298', '1-989', '1-999', '1-200');
foreach($strings as $string) {
$value = explode('1-', $string);
if($value[1] >= 201 & $value[1] <= 989) {
echo 'In range' . $string . "\n";
} else {
echo 'out of range' . $string . "\n";
}
}
輸出:
In range1-201
In range1-298
In range1-989
out of range1-999
out of range1-200
這應該工作,
1-(20[1-9]|2[1-9][0-9]|[3-8][0-9][0-9]|9[0-8][0-9])
交替,
1-(20[1-9]|2[1-9]\d|[3-8]\d{2}|9[0-8]\d)
來源: http : //www.regular-expressions.info/numericranges.html
我想我會像在C#中一樣執行以下操作。 實驗過
string tester = "1-201";
Match match = Regex.Match(tester, @"(?<one>1-)(?<Two>[0-9]{3})");
//MessageBox.Show(match.Groups[2].Value);
int x = Convert.ToInt32(match.Groups[2].Value);
if (x <= 201 && x > 989)
{
//Exclude those captures not necessary.
//Use the captures within the range.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.