Regular expression for no more than two repeated letters/digits

I have a requirement to handle a regular expression for no more than two of the same letters/digits in an XSL file.

  • no space
  • does not support special chars
  • support (a-z,A-Z,0-9)
  • require one of a-z
  • require one of 0-9
  • no more than 2 same letter/digits (i.e., BBB will fail, BB is accepted)

What I have so far

(?:[^a-zA-Z0-9]{1,2})

Solution 1:

This regex will do it: ^(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z])(?=.*\d)[A-Za-z0-9]+$

Here's the breakdown:

(?!.*([A-Za-z0-9])\1{2}) makes sure that none of the chars repeat more than twice in a row.

(?=.*[a-z]) requires at least one lowercase letter

(?=.*\d) requires at least one digit

[A-Za-z0-9]+ allows only letters and digits

EDIT : removed an extraneous .* from the negative lookahead

Solution 2:

(Partial solution) For matching the same character repeated 3 or more times consecutively, try:

([a-zA-Z0-9])\1{2,}

Sample matches (tested both here and here): AABBAA (no matches), AABBBAAA (matches BBB and AAA), ABABABABABABABA (no matches), ABCCCCCCCCCC (matches CCCCCCCCCC).

Solution 3:

Does this one work for you?

/(\b(?:([A-Za-z0-9])(?!\2{2}))+\b)/

Try it out:

var regex = new RegExp(/(\b(?:([A-Za-z0-9])(?!\2{2}))+\b)/)
var tests = ['A1D3E', 'AAAA', 'AABAA', 'abccddeeff', 'abbbc', '1234']

for(test in tests) {
   console.log(tests[test] + ' - ' + Boolean(tests[test].match(regex)))
}

Will output:

A1D3E - true
AAAA - false
AABAA - true
abccddeeff - true
abbbc - false
1234 - true