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
number = 561616161
I tried the below pattern but it is not accurate
^5(d)(?=d1).+
can someone point out what i am doing wrong?
Advertisement
Answer
I would use:
^(?=d{9}$)d*(d)(d)(?:12){3}d*$
Here is an explanation of the pattern:
- ^from the start of the number
- (?=d{9}$)assert exactly 9 digits
- d*match optional leading digits
- (d)capture a digit in- 1
- (d)capture another digit in- 2
- (?:12){3}match the XY combination 3 more times
- d*more optional digits
- $end of the number