I am working on mobile number of 9 digits.
I want to use regex to match numbers with pattern 5ABXYXYXY
.
A sample I have is 529434343
What I have tried
I have the below pattern to match it.
r"^\d*(\d)(\d)(?:\1\2){2}\d*$"
However, this pattern matches another pattern I have which is 5XXXXXXAB
a sample for that is 555555532
.
What I want I want to edit my regex to match the first pattern only 5ABXYXYXY
and ignore this one 5XXXXXXAB
CodePudding user response:
You can use
^\d*((\d)(?!\2)\d)\1{2}$
See the regex demo.
Details:
^
- start of string\d*
- zero or more digits((\d)(?!\2)\d)
- Group 1: a digit (captured into Group 2), then another digit (not the same as the preceding one)\1{2}
- two occurrences of Group 1 value$
- end of string.
CodePudding user response:
To match 5ABXYXYXY
where AB
should not be same as XY
matching 3 times, you may use this regex:
^\d*(\d{2})(?!\1)((\d)(?!\3)\d)\2{2}$
RegEx Breakup:
^
: Start\d*
: Match 0 or more digits(\d{2})
: Match 2 digits and capture in group #1(?!\1)
: Make sure we don't have same 2 digits at next position(
: Start capture group #2(\d)
: Match and capture a digit in capture group #3(?!\3)
: Make sure we don't have same digit at next position as in 3rd capture group\d
: Match a digit
- )`: End capture group #2
\2{2}
: Match 2 pairs of same value as in capture group #2$
: End