Vijay
Vijay

Reputation: 596

I need a regex for a telephone number which does not accept 0 as the first digit of the 3 digit US area code

I am currently working with the following regex to match a phone number

'\\([1-9]{3}\\)\\s{1}[0-9]{3}-[0-9]{4}'

But the above pattern is not allowing 0 in the first 3 digits and when I modify it to

'\\([0-9]{3}\\)\\s{1}[0-9]{3}-[0-9]{4}'

it is accepting 0 as the first digit. I would like to generate a regex which would not accept 0 for the first digit but does accept for the remaining digits.

I have modified the regex which I think will suit my needs but I am not entirely sure ( never ever did a regex pattern) and dont know how to test it on regex101

'\\([1-9]{1}[0-9]{2}\\)\\s{1}[0-9]{3}-[0-9]{4}'

if someone can help me out as in if you could point out if I am going in the right direction that would be amazing

I am looking for inverse of whats in this question, the answers in this make sure the number begins with a 0 but I am looking for inverse of the following implementation

Javascript Regex - What to use to validate a phone number?

Thank you, Vijay

Upvotes: 1

Views: 1027

Answers (2)

Eduardo Lynch Araya
Eduardo Lynch Araya

Reputation: 824

This Should Work.

Regexp:

[1-9]\d{2}\-\d{3}\-\d{4}

Input:

208-123-4567
099-123-4567
280-123-4567

Output:

208-123-4567
280-123-4567

JavaScript Code:

const regex = /[1-9]\d{2}\-\d{3}\-\d{4}/gm;
const str = `208-123-4567
099-123-4567
280-123-4567`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

See: https://regex101.com/r/3DKEas/1

Upvotes: 1

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

Try this:

/\([1-9]\d\d\)\s\d{3}-\d{4}/;

Or:

new RegExp('\\([1-9]\\d\\d\\)\\s\\d{3}-\\d{4}');

Explanation:

\(    : open paren
[1-9] : a digit (not 0)
\d\d  : 2 digits (including 0)
\)    : close paren
\s    : one space
\d{3} : 3 digits (including 0)
-     : hyphen
\d{4} : 4 digits (including 0)

Upvotes: 3

Related Questions