phone # 带区号的国家代码的正则表达式
Regex for phone # country code with area code
我需要一个正则表达式来匹配这个国家代码 + 区号 phone # 格式:
1-201
其中前两个字符始终是 1-
,最后 3 个字符是 201
和 989
之间的数字。
我目前有 ([1][\-][0-9]{3})
来指定 1-xyz
和限制长度,但我怎样才能让最后一组来限制这些范围?
这将在 PHP 中使用。
使用这个正则表达式:
^1\-(2\d[1-9])|([3-8]\d{2})|(9[0-8]\d)$
下面是对三个捕获的解释groups/ranges:
(2\d[1-9])
匹配 201
到 299
([3-8]\d{2})
匹配 300
到 899
(9[0-8]\d)
匹配 900
到 989
这是一个 link,您可以在其中测试此正则表达式:
更新:
显然 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)
我想我会像在 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.
}
我需要一个正则表达式来匹配这个国家代码 + 区号 phone # 格式:
1-201
其中前两个字符始终是 1-
,最后 3 个字符是 201
和 989
之间的数字。
我目前有 ([1][\-][0-9]{3})
来指定 1-xyz
和限制长度,但我怎样才能让最后一组来限制这些范围?
这将在 PHP 中使用。
使用这个正则表达式:
^1\-(2\d[1-9])|([3-8]\d{2})|(9[0-8]\d)$
下面是对三个捕获的解释groups/ranges:
(2\d[1-9])
匹配 201
到 299
([3-8]\d{2})
匹配 300
到 899
(9[0-8]\d)
匹配 900
到 989
这是一个 link,您可以在其中测试此正则表达式:
更新:
显然 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)
我想我会像在 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.
}