tubidubi tubidubi - 11 months ago 46
Java Question

Regex password - small letter cannot be followed by small letter and vice versa

So the specification is:

  • 10 to 15 characters

  • has at least 1 small letter

  • has at least 1 big letter

  • cannot have 2 small or 2 big letters in a row (small letter cannot be followed by small letter and big letter cannot be followed by big letter)

I thought that I could do this by having 5 to 7 pairs of characters and 1 optional at the beginning, so that gives 10 to 15 characters, but these (and many other tests) return false every time. Any ideas on the approach or maybe syntax is incorrect?


// regex expression
private static final Pattern PASSWORD_PATTERN = Pattern.compile("^([a-z0-9]?([A-Z0-9][a-z0-9]){5,7})
| ([A-Z0-9]?([a-z0-9][A-Z0-9]){5,7})$");

// testing
public static void main(String args[]) {
// function for checking
static boolean verifyPassword(String password) {
final Matcher matcher = PASSWORD_PATTERN.matcher(password);
return matcher.matches();

Answer Source

With a .matches() method that requires a full string match, you may use



  • ^ - implicit since the pattern is used inside .matches() method - start of string
  • (?=[^A-Z]*[A-Z]) - there must be an uppercase ASCII letter after any 0+ chars other than uppercase ASCII letters
  • (?=[^a-z]*[a-z]) - there must be a lowercase ASCII letter after any 0+ chars other than lowercase ASCII letters
  • (?!.*(?:[A-Z]{2}|[a-z]{2})) - no 2 consecutive uppercase ([A-Z]{2}) or lowercase ([a-z]{2}) letters after any 0+ chars other than line break chars (.*)
  • \\p{Alnum}{10,15} - 10 to 15 ASCII letters or digits
  • $ - implicit - end of string.

See a Java demo:

List<String> strs = Arrays.asList("aaaa", "zzzzzzz", "AaAaAaAaAaAa3", "123456789123");
String pat = "(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?!.*(?:[A-Z]{2}|[a-z]{2}))\\p{Alnum}{10,15}";
for (String str : strs)
    System.out.println(str + ": " + str.matches(pat));


aaaa: false
zzzzzzz: false
AaAaAaAaAaAa3: true
123456789123: false
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download