2

I'm working regex in recent days and now need to make regex which is match with 2 digit but the digits should be different each other For example followings will be matched: 56, 78, 20 ... But followings should not be matched: 22, 33, 66 or 99

Already wasted few days for this solution. So any suggestion will be welcome.

rener172846
  • 431
  • 1
  • 6
  • 19

1 Answers1

5

Capture the first digit, then use negative lookahead with a backreference to that first digit to ensure it isn't repeated:

(\d)(?!\1)\d

https://regex101.com/r/AxH6s8/1

If you need a named group instead:

(?<first>\d)(?!\k<first>)\d

For a general solution of n digits in a row without any repeated digits, you can do something similar, except put \d* inside the negative lookahead, before the backreference:

^(?:(\d)(?!\d*\g{-1}))+$

https://regex101.com/r/AxH6s8/2

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • good work. but would you make an example with named group? because my regex is so complex and I can't index them as "\1" or "\2" simply. – rener172846 Jul 28 '18 at 22:30
  • Not sure what language you're using, but you can use `(?\d)(?!\k)\d` – CertainPerformance Jul 28 '18 at 22:30
  • I'm using php, and I can't share full regex here. How about to name the first digit as "FirstDigit" such as following `(?'FirstDigit'[0-9])(?!(FirstDigit))[0-9]` Of course this isn't work so I need to fix that correctly – rener172846 Jul 28 '18 at 22:38
  • 1
    @rener172846 Another alternative is to use a relative backreference, e.g. `(\d)(?!\g{-1})\d` which can save naming things you don't otherwise need to. – user3942918 Jul 28 '18 at 22:48
  • @CertainPerformance if the length of digit isn't fixable, is that still possible with only regex? For example, the number can be any of 4 - 8 digit, and there shouldn't be any same value. so 1245, 24567, 46735 are all match, but 11456, 145467 or 356787 are not match. – rener172846 Jul 29 '18 at 05:59