Jared Eitnier
Jared Eitnier

Reputation: 7152

Regex for phone # country code with area code

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

Answers (4)

Unnikrishnan
Unnikrishnan

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

Tim Biegeleisen
Tim Biegeleisen

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:

Regex101

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

DarkSigma
DarkSigma

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

chris85
chris85

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

Related Questions