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.

PythonSecurity Boundaries

Code

pythonsnippet
19 lines
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

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`.