rener172846
rener172846

Reputation: 451

Regex to match 2 digit but different numbers

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.

Upvotes: 2

Views: 171

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

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

Upvotes: 5

Related Questions