首页 > 解决方案 > 我尝试编写的 Python 密码生成器不起作用,但没有错误消息

问题描述

我正在尝试通过用户输入使其与正则表达式一起使用,但它不起作用,没有错误消息。也许我的 if 语句没有得到认可?


print(“type password”)
password =input()

pattern=r”([0-10000000][a-z][A-Z])”

match=re.search(pattern,password)

if match and (len(password)<9) and (len(password)>4):
    print(“password is strong”)
else: 
    print(“password should have at least one letter, number, and capital letter included and be between 5 and 8 characters long”)```

标签: pythonpasswords

解决方案


让我们看看您当前的正则表达式([0-10000000][a-z][A-Z])

  1. [0-10000000]匹配 0-1 范围内的单个字符或字符0.
  2. [a-z]然后匹配 az 范围内的单个字符。
  3. [A-Z]匹配 AZ 范围内的单个字符。

总而言之:匹配数字 0 或 1,后跟一个小写字母,再跟一个大写字母。这与你的意图完全不同。


我想出的正则表达式是这样的:^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-z]{5,8}$. 我将它保存在 Regex101 上,以便您可以轻松查看它的作用并对其进行测试。

这是一个示例程序:

import re

pwd_patt = re.compile(r"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\da-zA-z]{5,8}$")

test_strs = ["Amc01", "Ac", "aa0aa", "aa0aaAadwaw", "ghG789"]

for curr_str in test_strs:
    print(curr_str, pwd_patt.fullmatch(curr_str))

输出:

Amc01 <re.Match object; span=(0, 5), match='Amc01'>
Ac None
aa0aa None
aa0aaAadwaw None
ghG789 <re.Match object; span=(0, 6), match='ghG789'>

推荐阅读