Course contentsShow
← Java
Lesson 2286 of 2,87044. Regular ExpressionsFree lesson

Password Strength Validation

Use lookaheads to enforce password rules: minimum length, uppercase, lowercase, digits, and special characters.

Password Strength Validation

You'll learn how to use regex lookaheads to enforce complex password requirements in a single pattern.

When validating passwords, you often need to check multiple independent criteria: minimum length, at least one uppercase letter, one lowercase letter, one digit, and one special character. Regular expressions with lookaheads let you enforce all these rules simultaneously without writing separate checks.

Understanding Lookaheads for Password Rules

A lookahead ((?=...)) checks if a pattern exists ahead in the string without consuming characters. This means you can chain multiple lookaheads at the start of your pattern, each verifying a different requirement:

String passwordPattern = "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[@#$%^&+=]).{8,}$";

Let's break this down:

  • ^ — Start of string
  • (?=.*[A-Z]) — Lookahead: must contain at least one uppercase letter
  • (?=.*[a-z]) — Lookahead: must contain at least one lowercase letter
  • (?=.*\\d) — Lookahead: must contain at least one digit
  • (?=.*[@#$%^&+=]) — Lookahead: must contain at least one special character
  • .{8,} — Actually match 8 or more characters (minimum length)
  • $ — End of string

Practical Example

Pattern pattern = Pattern.compile("^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[@#$%^&+=]).{8,}$");

Matcher matcher1 = pattern.matcher("Weak123");
System.out.println(matcher1.matches()); // false (no special char)

Matcher matcher2 = pattern.matcher("Str0ng@Pass");
System.out.println(matcher2.matches()); // true (all rules satisfied)

Matcher matcher3 = pattern.matcher("short1@A");
System.out.println(matcher3.matches()); // true (meets all requirements)

The beauty is that all checks happen in one validation pass—each lookahead independently confirms its rule while the final .{8,} enforces the length.

Key Takeaway: Lookaheads enable elegant multi-criteria password validation by checking multiple independent conditions in a single regex pattern without consuming characters.