Home > Mobile >  Regex Capture a matching group twice
Regex Capture a matching group twice

Time:09-20

I have been looking at a lot of questions but none of them answered my problem.

I am trying to identify vanity/special mobile numbers consisting of 9 digits.

I have this pattern of two numbers repeating for 4 times each

5XXXXYYYY 

I was able to write a regex that catches the first group 'XXXX'. However, I am not able to acpture the second one 'YYYY'.

This is the regex I have tried so far

(\d)\1{3}

[0-9]{4,5}

I tried it on the below number, it returns '1111' and ignores '2222'

511112222

Is there a way to repeat the capture to include both groups

Thank you

CodePudding user response:

You may use this regex:

^5((\d)\2{3})((\d)\4{3})$

RegEx Demo

RegEx Breakup:

  • ^: Start
  • 5: Match 5
  • (: Start capture group #1
    • (\d): Match a digit in capture group #2
    • \2{3}: Repeat value captured in group #2 exactly 3 times
  • ): End capture group #1
  • (: Start capture group #3
    • (\d): Match a digit in capture group #4
    • \4{3}: Repeat value captured in group #4 exactly 3 times
  • ): End capture group #3
  • $: End
  • Related