【问题标题】:re.search password checking errorre.search 密码检查错误
【发布时间】:2015-01-05 13:46:54
【问题描述】:

我的代码正在运行,但定义强密码的第一行代码导致其余代码返回为空。例如,当第一行代码正在搜索一个数字字符时,从那里开始的任何代码都会导致代码在满足要求的情况下不打印消息。如果我将它从搜索数字更改为搜索大写或小写字符,那么如果代码需要查找大写或小写等,则之后的任何编码都将不起作用。

import re
password = str(input("Please enter the password you wish to test the strength of.\n"))
if re.search(r'[0-9]', password): 
    if re.search(r'[A-Z]', password):
        if re.search(r'[a-z]', password):
            print("Your password strength is STRONG.")
elif re.search(r'[a-z]', password) and re.search(r'[A-Z]', password):
    print("Your password strength is MEDIUM.")
elif re.search(r'[0-9]', password) and re.search(r'[A-Z]', password):
    print("Your password strength is MEDIUM.")
elif re.search(r'[a-z]', password) and re.search(r'[0-9]', password):
    print("Your password strength is MEDIUM.")
elif re.search(r'[A-Z]', password) or re.search(r'[a-z]', password) or re.search(r'[0-9]', password):
    print("Your password strength is WEAK.")

【问题讨论】:

  • 密码长度是否会影响您在此处给出的强度等级?
  • 如果密码在 6 到 12 个字符之间,则只测试强度。但是长度不影响强度,它只是它具有的字符。

标签: python regex passwords character


【解决方案1】:

使用密码“9gag”自行执行代码逻辑。那里有一个[0-9],但不是一个[A-Z]。解释器输入第一个if,因此被排除在随后的elifs 之外,但它没有进入嵌套的if 并陷入困境。

这种方法可能更简单:

hits = [ re.search(r'[0-9]', password) != None, re.search(r'[A-Z]', password) != None, re.search(r'[a-z]', password) != None ]
strength = sum( hits )

【讨论】:

  • 现在这就是我所说的开箱即用的方法,bool 在 python 上被视为 int,尽管对于刚刚学习的人来说理解起来可能有点复杂。
  • 是的。然后澄清一下:每个术语re.search( pattern, passord ) != None 产生True(匹配)或False(不匹配)。在sum 中,与许多其他数值运算一样,True 被视为 1,False 被视为 0,例如,sum( [ True, True, False ] ) 为 2。
【解决方案2】:

你可以把它重构成这样的

import re
strength = 0
password = str(input("Please enter the password you wish to test the strength of.\n"))
if re.search(r'[0-9]', password):
    strength += 1
if re.search(r'[A-Z]', password):
    strength += 1
if re.search(r'[a-z]', password):
    strength += 1

if strength == 3
    print("Your password strength is STRONG.")

if strength == 2:
    print("Your password strength is MEDIUM.")

if strength == 1:
    print("Your password strength is WEAK.")

虽然,我确信有更好的方法,请尝试跳出框框:D

【讨论】:

  • 如果我同时使用 password.isupper 或 password.islower 或 password.isdigit,该方法是否有效?
  • 很可能不会,例如 jez 所说的“9gag”,对于所有这些方法都将返回 False。太糟糕了,没有 hasupper、haslower 或 hasdigit 方法
【解决方案3】:

我曾经尝试实现一个更高级的密码强度算法(涉及香农熵及其修改),但最后我发现这是一个难题,并且不能真正说出密码何时是好的.

您可能唯一可以轻松确定的是密码何时真的很糟糕。

所以也许只是教育用户明智地选择密码或者在适当的时候创建随机密码是最好的。

对密码设置任意规则通常很烦人。例如。如果有人使用密码管理器生成随机密码,他们可能会违反您的规则,但仍然是好的密码,因为它们是随机的。

【讨论】:

    猜你喜欢
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2010-10-17
    • 2018-05-19
    • 1970-01-01
    相关资源
    最近更新 更多