实现说明
本示例的循环部分是 for password in ["hunter2", "Hunter2", "Hunter2!", "s3cure-pass"]。
演示用的数据放在这几个模块级绑定中:policy、accepted。
使用要点
- 跑完文件,输出里会留下标记——
policy accepts:。
常见问题
除了语言工具链还要下载什么吗?
除了这个语言的工具链,什么都不用再下载。 全部导入都来自标准库:re。 状态都挂在模块顶层:policy、accepted。
核心语句
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")
代码示例
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)