Enforcing Password Complexity with Lookaheads
Password validation is the perfect use case for Positive Lookaheads. You want to check multiple conditions against the same string without consuming it.
The "All-in-One" Pattern
Let's enforce: 1 Uppercase, 1 Lowercase, 1 Digit, 1 Special Char, Min 8 chars.
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
How it works
The engine stands at the start of the string (^) and looks ahead checks each condition sequentially:
(?=.*[a-z]): "Do I see a lowercase letter ahead?" (Yes/No)(?=.*[A-Z]): "Do I see an uppercase letter ahead?" (Yes/No)- If all checks pass, it finally attempts to match the content structure
[...] {8,}.