RegEx to allow 9 numbers but block any more than 4 duplicate numbers

Viewed 658

I am looking for assistance with finding a RegEx to require exactly 9 numbers but block any more than 4 duplicate numbers in a row. If more or less than 9 characters are entered it should fail.

Examples would be:

  • 123456789 - allowed
  • 111156789 - allowed
  • 121314151 - allowed
  • 111116789 - not allowed
  • 123499999 - not allowed

I've tried the following with no luck:

/^(?!.*(\d)\1{5})(\d{9})*$/
3 Answers

Block any digit, that repeats 5 times in row:
/^(?:(\d)(?!\1{4})){9}$/

Explanation:

(\d) - first group, that matches any digit.
\1 - repeats first group contents.
(\d)(?!\1{4}) - block digit, that have 4 same digits after it.
(?:(\d)(?!\1{4})){9} - match only 9 of this patterns (each contain only one digit)

Example:

let reg = /^(?:(\d)(?!\1{4})){9}$/;

console.log(reg.test("123456789"));  // -> true
console.log(reg.test("111116789"));  // -> false
console.log(reg.test("12345678"));   // -> false
console.log(reg.test("1234567890")); // -> false

/(?=(?!(\d)\1{4}))^\d{9}$/

Explanation:

(\d)\1{4} - 5 repeating digits of the same number

(?!(\d)\1{4}) - Don't match 5 of the same number

(?=(?!(\d)\1{4})) - Make sure the expression doesn't include 5 digits of the same number, then return to the original starting point for further matching

^\d{9}$ - Match an expression that is 9 digits total

You can use this regex, which rejects the match, ONLY IF, any digit is repeated at least 5 times.

/^(?!\d*(\d)\1{4})\d{9}$/

Explanation:

  • ^ --> Start of string
  • (?!\d*(\d)\1{4}) --> Negative look ahead, that rejects the match if any digit in the string is repeated at least five times.
  • \d{9} --> Matches exactly nine digits
  • $ --> End of string

Demo

Here is a javascript code for same,

let regex = /^(?!\d*(\d)\1{4})\d{9}$/;
var strs = ["123456789","111156789","121314151","111116789","123499999","888888888","199999991","123327333"];

for (var i=0;i<strs.length;i++) {
    console.log(strs[i] + " --> " + regex.test(strs[i]));
}

Related