1

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

Community
  • 1
  • 1
Vijay
  • 600
  • 6
  • 16

2 Answers2

3

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)
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • That is a great explanation but I am not sure if I am testing it correctly on www.regex101.com the phone number i am entering to test as per your explanation is (200) 123-4567 and the test fails, am I doing something wrong ? – Vijay Feb 22 '17 at 19:52
  • @Vijay One note: If you are using this regex to test if a string is a valid number (`regex.test(string)`) then you may want to add anchors at the beginig (`^`) and the end (`$`) like this: `/^\([1-9]\d\d\)\s\d{3}-\d{4}$/`. – ibrahim mahrir Feb 22 '17 at 19:57
1

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