Search code examples
regex

regex for matching 5 digit numbers, starting with specific digits, but not allowing all repetitions


I will use JavaScript and this is the rules that I need to match:

  • numbers must have exactly 5 digits
  • numbers can only start with 1-4 and 6-9
  • numbers cannot have all digits repeatable

So:

12345  - match
11111  - no match (the same digit is repeated 5x
22220  - match
59876  - no match (starts with the digit 5)
90279  - match
899991 - no match (6 digits)

Here is my exploration of the regex pattern:

^(?!(\d)\1{4,})\d{5}$

The problem is that I don't know how to force it to have the first digit as [1-4,6-9].

Any help would be appreciated.


Solution

  • You can simply add a lookahead for starting with ^[1-46-9], if your pattern works:

    (?=^[1-46-9])^(?!(\d)\1{4,})\d{5}$
    

    or you can make the following change:

    ^(?!(\d)\1{4,})[1-46-9][0-9]{4}$