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
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.
"?=" 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: