Regex Lookaheads Compose Password Policies
Each lookahead assertion inspects one requirement without consuming characters, so a single combined pattern can enforce several password rules at once.
Code
import re
# 每条 lookahead 断言 (?=...) 零宽检查位置、不消耗字符,规则彼此独立
RULES = {
"eight chars": re.compile(r".{8,}"),
"lowercase": re.compile(r"(?=.*[a-z])"),
"uppercase": re.compile(r"(?=.*[A-Z])"),
"digit": re.compile(r"(?=.*\d)"),
"symbol": re.compile(r"(?=.*[!@#$%])"),
}
for password in ["hunter2", "Hunter2", "Hunter2!", "s3cure-pass"]:
failed = [name for name, rule in RULES.items() if not rule.search(password)]
print(password, "fails:", failed or "none")
# 把所有 lookahead 串进同一个正则就是 and 语义的组合策略
policy = re.compile(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$")
accepted = [p for p in ["Hunter2", "hunter2x", "HUNTER2X", "Hunter22"] if policy.fullmatch(p)]
print("policy accepts:", accepted)Output
Captured from a sandboxed run of this snippet in the build pipeline.
hunter2 fails: ['eight chars', 'uppercase', 'symbol']
Hunter2 fails: ['eight chars', 'symbol']
Hunter2! fails: none
s3cure-pass fails: ['uppercase', 'symbol']
policy accepts: ['Hunter22']How the snippet works
Repetition is confined to for password in ["hunter2", "Hunter2", "Hunter2!", "s3cure-pass"] — the rest of the file is straight-line.
Module-level bindings hold the data — policy, accepted — with no function scope in between.
Using it
The demo output is labeled (policy accepts:), so every printed line maps back to its originating operation.
Key statements
for password in ["hunter2", "Hunter2", "Hunter2!", "s3cure-pass"]:
failed = [name for name, rule in RULES.items() if not rule.search(password)]
print(password, "fails:", failed or "none")
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Password Entropy EstimatorEstimate a password's alphabet size and Shannon entropy in bits, then translate that into offline crack times at realistic guessing rates.Password Strength MeterScore a password from 0 to 100 based on length and character classes, and get clear suggestions to make it stronger. Everything runs locally.
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `re`. Its state lives in module-level bindings: `policy`, `accepted`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.