Password Policy Strength Check Regex for Python
/^(?=.*[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 Python. 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 Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.
Python Implementation
# Password Policy Strength Check
# ReDoS-safe | RegexVault — Security > Password Formats
import re
password_policy_strength_check_pattern = re.compile(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~`])(?!.*\s).{12,128}$')
def validate_password_policy_strength_check(value: str) -> bool:
return bool(password_policy_strength_check_pattern.fullmatch(value))
# Example
print(validate_password_policy_strength_check("Correct!Horse#Battery9")) # TrueTest 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 Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. 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