I am trying to write a regex pattern for phone numbers consisting of 9 fixed digits.
I want to identify numbers that have two numbers alternating for four times such as 5XYXYXYXY
I used the below sample
JavaScript
x
2
1
number = 561616161
2
I tried the below pattern but it is not accurate
JavaScript
1
2
1
^5(d)(?=d1).+
2
can someone point out what i am doing wrong?
Advertisement
Answer
I would use:
JavaScript
1
2
1
^(?=d{9}$)d*(d)(d)(?:12){3}d*$
2
Demo
Here is an explanation of the pattern:
^
from the start of the number(?=d{9}$)
assert exactly 9 digitsd*
match optional leading digits(d)
capture a digit in1
(d)
capture another digit in2
(?:12){3}
match the XY combination 3 more timesd*
more optional digits$
end of the number