Validate US Telephone Numbers-lookahead

Validate US Telephone Numbers-lookahead
0

#1

Tell us what’s happening:
Hi everyone ,

Can someone please explain what’s wrong wth the below expression
I would like to match the number 1 555 555 555

My regular expression is as below
var regxi = /\d?\s?(?(?=\d{3}))\d{3}[-)\s]\d{3}[-)\s]\d{4}[-)\s]/

Is it possible to use the ? quantifier with lookaheads? I think the issue is somewhere there…

Many Thanks

Your code so far

function telephoneCheck(str) {
  // Good luck!
  
  var regxi =  /\d?\s?\(?(?=\d{3}\))\d{3}[-)\s]\d{3}[-)\s]\d{4}[-)\s]/;
  
  return regxi.test(str);
}



telephoneCheck("1 555 555 5555");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36.

Link to the challenge:


#2

hi, just solved this today.
It helped me when I gruopped the optional chars.
I used this like /^REGEXP$/, so no lookaheads needed, just the pattern itself. mstch it from the beginning and from the end of the string.


#3

Hello reinelic,

I remember how much skull sweat learning regex cost me (both the first time in PERL, years ago, and now again for web dev). Here are the links I found helpful when learning them, especially regexr.

Regexr: Testing site, much like codepen or jsfiddle - uses coloring and explains step-by-step what is going on in what you write

Quick table of regex operators

In-depth tutorial, looks very granularly at the regex engine, uses colors to illustrate concepts

To get you started on the path to regex mastery, here’s a regexr for the givens you’ve provided


#4

the optional digit at the beginning will let any numbers passed.


#5

I show you the first chunk of my regEx.

^((1\s?)?((\(\d{3}\)(\s|-)?)|(\d{3}(\s|-)?))

^()$ the entire stuff sits in this. That’s why the first parentheses has no closing pair.
This checks the 1 (555) part
() chars needs to be escaped.


#6

You have two lookaheads, but no actual pattern to match. A while ago I posted some great tools to help you learn regular expressions: