Regex to match phone number 5ABXXYYZZ

Question:

I am using regex to match 9 digits phone numbers.

I have this pattern 5ABXXYYZZ that I want to match.

What I tried

I have this regex that matches two repetitions only 5ABCDYYZZ

S_P_2 = 541982277
S_P_2_pattern = re.sub(r"(?!.*(d)1(d)2(d)3).{4}d(d)4(d)5", "Special", str(S_P_2))
print(S_P_2_pattern)

What I want to achieve

I would like to update it to match three repetitions 5ABXXYYZZ sample 541882277

Asked By: Leena

||

Answers:

Try:

^5dd(?:(d)1(?!.*1)){3}$

See an online demo

  • ^5dd – Start-line anchor and literal 5 before two random digits;
  • (?:(d)1(?!.*1)){3} – Non-capture group matched three times with nested capture group followed by itself directly but (due to negative lookahead) again after 0+ chars;
  • $ – End-line anchor.
Answered By: JvdV
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.