Check digits with regex, only the last one element can occur 2 times

Viewed 94

I tried to check a number with regex, where only the last digit can occur twice.

Using javascript as programming language, tried many combinations on https://regex101.com/ but I was able do define only unique characters, like

(?:([1-9])(?!.*\1)){8}

but I am in trouble with the last one digit.

characterset: [1-9]

important : 0 is not in the characterset, therefore "\d" cannot work, only [1-9].

examples:

123456782 -> true, last digit (2) occur twice (EXACTLY), no other repeated digits
189765432 -> false, last digit not repeated previously, only unique digits in it
123456889 -> false, not the last digit repeated
123476782 -> false, not only the last digit repeated
123426282 -> false, last digit repeated more than twice.

Any help would be welcomed. How to apply a regex for it?

1 Answers

You can use

^(?=[1-9]+([1-9])$)(?!.*(?!\1)(\d).*\2)(?:(?!\1)\d)*\1(?:(?!\1)\d)*\1$

A little shortened:

^(?=[1-9]+([1-9])$)(?!.*(?!\1)(\d).*\2)(?:(?:(?!\1)\d)*\1){2}$

See the regex demo #1 and regex demo #2.

Note you can use \d in the non-initial lookahead since the initial lookahead validates the string format, namely, there can only be two more non-zero digits.

Details

  • ^ - start of a string
  • (?=[1-9]+([1-9])$) - right from the start of string, there should be one or more non-zero digits followed with a non-zero digit at the end of string that is captured into Group 1. We'll be able to refer to this value using the \1 backreference
  • (?!.*(?!\1)(\d).*\2) - immediately to the right of the current location, there can be no digit that is not equal to the one captured into Group 1 that is repeated
  • (?: - start of a non-capturing group:
    • (?:(?!\1)\d)* - any digit, zero or more occurrences, as many as possible, that is not the one that was captured into Group 1
    • \1 - the captured digit
  • ){2} - end of the non-capturing group, repeat 2 times
  • $ - end of string.
Related