Password Policy Strength Check Regex for Java
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~`])(?!.*\s).{12,128}$/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching password policy strength check, ported and verified for Java. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.
Java Implementation
// Password Policy Strength Check
// ReDoS-safe | RegexVault — Security > Password Formats
import java.util.regex.Pattern;
public class PasswordPolicyStrengthCheckValidator {
private static final Pattern PATTERN =
Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()_+\\-=\\[\\]{};\':\"\\\\|,.<>\\/?~`])(?!.*\\s).{12,128}$");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("Correct!Horse#Battery9")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
Correct!Horse#Battery9 | password123 |
P@ssw0rd_Secur3! | Password1 |
MyStr0ng!Password#2024 | SHORT!1Aa |
| — | NoSpecialChar123 |
| — | Has Spaces!A1b |
When to use this pattern
This pattern is drawn from the Security > Password Formats category and is provided for complex validation requirements. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
NIST 800-63b now recommends checking passwords against breach databases (HaveIBeenPwned Pwned Passwords API) rather than enforcing arbitrary complexity. Long passphrases that fail complexity checks are often stronger than short complex passwords.
Technical Notes
NIST SP 800-63b (2017) de-emphasized complexity rules in favor of length and breach database checking. This pattern implements the more traditional complexity approach. Minimum 12 characters is NIST-aligned. 128-char maximum prevents DoS via extremely long inputs.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern