Home > database >  How to match a repeated character sequence with Regular Expression (regex)
How to match a repeated character sequence with Regular Expression (regex)

Time:12-03

I want to capture all repeated numbers groups

  • if i have 1115555666777
  • I want to capture this (111)(5555)(666)(777)
  • I feel this is not the best way to achive what i want any idea to improve this regex?
  • [1] |[2] |[3] |[4] |[5] |[6] |[7] |[8] |[9]

CodePudding user response:

Thanks all of you, the answer that worked for me was: ([0-9])\1* Thanks, again :D

CodePudding user response:

You can use a capture group for a single digit ([1-9]) and optionally repeat a backreference \1* containing the same value as the group.

The optional part * is due to that in your pattern you repeat the number 1 or more times. The 1 time you already have in the capture group.

The pattern:

[1] |[2] |[3] |[4] |[5] |[6] |[7] |[8] |[9] 

Can be written as

1 |2 |3 |4 |5 |6 |7 |8 |9 

Can be written as

([1-9])\1*

Or if the zero is also allowed, can be written as:

([0-9])\1*

See a regex demo for digits 1-9

  • Related