skip to Main Content

I am not understanding why this regex pattern is not matching as expected. I am testing this pattern on https://regexr.com.

regex =/^1?((?=d{3}))[-. ]?(d{3})$/
sample = 1(123) 123

My understanding is first pattern should be number 1 or nothing then 3 digits in closed parentheses or no parentheses at all. There should not be open parentheses which will be the case when we only use (?(d{3}))? and after [-. ] which is optional, followed by 3 digits end.

2

Answers


  1. Lookahead doesn’t consume symbols. As a result, regex like this ((?=d{3}))[-. ] require, that on one hand, ( is followed by three digits and ), but on the other hand followed by either of dash, dot or space.

    In your case, you don’t need lookaheads at all, simple ^1?(d{3})[-. ]?(d{3})$ should work.

    Demo here.

    Login or Signup to reply.
  2. "?=" is ruining your regex since you want to catch those 3 digits.
    If you want to make paranthesis optinoal but you dont want any open one, you should create to cases then.

    check that one if u solve your issue:

    regex=/^1?(((d{3}))||(d{3}))[-. ]?(d{3})$/
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search