Reputation: 7152
I need a regex to match this country-code + area code phone # format:
1-201
where the first two characters are always 1-
and the last 3 characters are digits between 201
and 989
.
I have ([1][\-][0-9]{3})
currently to specify the 1-xyz
and limit length but how can I have the last group to restrict those ranges?
This will be used in PHP.
Upvotes: 1
Views: 1196
Reputation: 563
I think I would do it like the following in C#. Experimented.
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.
}
Upvotes: 0
Reputation: 520878
Use this regex:
^1\-(2\d[1-9])|([3-8]\d{2})|(9[0-8]\d)$
Here is an explanation of the three capturing groups/ranges:
(2\d[1-9])
matches 201
to 299
([3-8]\d{2})
matches 300
to 899
(9[0-8]\d)
matches 900
to 989
Here is a link where you can test this regex:
Update:
Apparently Laravel doesn't like having so many nested capture groups, but this simplification should work for your needs:
1-(2\d[1-9]|[3-8]\d{2}|9[0-8]\d)
Upvotes: 2
Reputation: 416
This should work,
1-(20[1-9]|2[1-9][0-9]|[3-8][0-9][0-9]|9[0-8][0-9])
Alternately,
1-(20[1-9]|2[1-9]\d|[3-8]\d{2}|9[0-8]\d)
source: http://www.regular-expressions.info/numericranges.html
Upvotes: 1
Reputation: 23892
I would not use a regex for this. It is going to be messy and hard to maintain.
I would do something like this:
$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";
}
}
Output:
In range1-201
In range1-298
In range1-989
out of range1-999
out of range1-200
Upvotes: 1