1

I am trying to write a regular expression that will match a two digit number where the two digits are not same.

I have used the following expression:

^([0-9])(?!\1)$

However, both the strings "11" and "12" are not matching. I thought "12" would match. Can anyone please tell me where I am going wrong?

Saptarshi Basu
  • 8,640
  • 4
  • 39
  • 58

1 Answers1

5

You need to allow matching 2 digits. Your regex ^([0-9])(?!\1)$ only allows 1 digit string. Note that a lookahead does not consume characters, it only checks for presence or absence of something after the current position.

Use

^(\d)(?!\1)\d$
           ^^

See demo

Explanation of the pattern:

  • ^ - start of string
  • (\d) - match and capture into Group #1 a digit
  • (?!\1) - make sure the next character is not the same digit as in Group 1
  • \d - one digit
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563