Home > Mobile >  Match Phone Number using Regex 5X000Y000
Match Phone Number using Regex 5X000Y000

Time:10-12

I am trying to match the pattern 5X000Y000 of 9 digit number.

What I have tried

I have written the below regex

B_5 = 530004000

B_5_pattern = re.sub(r'^5(\d(000))(\d(000))', "Bronze", str(B_5))

print(B_5_pattern)

What I want to achieve

I want to update my regex to add a condition that X000 can not be the same as Y000. (X!=Y).

So the regex will match 530004000 but will not match 530003000

CodePudding user response:

You could use:

B_5 = "530004000"
if re.search(r'^5(\d)0{3}(?!\1)\d0{3}$', B_5):
    print("MATCH")

CodePudding user response:

You may use this regex:

^5(\d)0{3}(?!\1)\d0{3}$

RegEx Demo

RegEx Breakdown:

  • ^: Start
  • 5: Match digit 5
  • (\d): Match a digit and capture in group #1
  • 0{3}: Match 3 zeroes
  • (?!\1): Make sure next digit is not same as that of captured group #1
  • \d: Match a digit
  • 0{3}: Match 3 zeroes
  • $: End
  • Related