【问题标题】:Regex Sequence Strong Password [duplicate]正则表达式序列强密码[重复]
【发布时间】:2021-07-26 19:05:01
【问题描述】:

我想测试输入值是否符合条件:

  • 至少一个小写字母
  • 至少一个大写字母
  • 至少一位数
  • 至少有一个字符不是 \w

我编写的正则表达式似乎只遵循这个特定的顺序,例如: abCD99$%

但如果我打乱了序列,正则表达式就不再起作用了: CD99ab$%

请问有大神知道是什么问题吗?提前干杯。

import re

# Asks user for an input

print('Please enter a password for checking its strength:')

pwd = input('> ')

#Test the input to see if it is more than 8 characters

if not len(pwd) < 8:
    pwdRegex = re.compile(r'([a-z]+)([A-Z]+)([0-9]+)(\W+)')     #order problem
    if not pwdRegex.search(pwd) == None:
        print('Password OK.')
    else:
        print('Please make sure password fulfills requirements!')
else:
    print('Characters must not be less than 8 characters!')

【问题讨论】:

  • 正确使用正向前瞻可以解决该问题。我认为在 SO 上有很多例子。
  • 为每个标准使用单独的正则表达式要容易得多。
  • 请参考这个答案:stackoverflow.com/questions/1559751/…
  • @Thomas 仅在您不熟悉正则表达式时使用 :-)

标签: python regex


【解决方案1】:

在您的情况下,我认为在没有正则表达式的情况下进行验证可能是一个很好的解决方案:

def isGoodPassword(password):
  # contains upper and lower, digit and special char
  return (not password.islower()
         and not password.isupper()
         and any(c.isdigit() for c in password) 
         and any(not c.isalnum() for c in password))


isGoodPassword('hello') # False
isGoodPassword('Hello!') # False
isGoodPassword('Hello!1') # True

【讨论】:

    【解决方案2】:

    您需要使用前瞻来验证您的要求:

    (?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\W)^.+$
    
    • (?=.*[a-z]) - 确保我们在某处有一个小写字符
    • (?=.*[A-Z]) - 确保我们在某处有一个大写字符
    • (?=.*[0-9]) - 确保我们在某处有一个数字
    • (?=.*\W) - 确保我们在某处有非\w
    • ^.+$ - 上述所有要求都已满足,因此让我们捕获整条生产线
      • 如果您只是进行通过/失败测试并且不需要捕获任何内容,则可以省略此部分

    https://regex101.com/r/HdfVXp/1/

    【讨论】:

      【解决方案3】:

      https://pypi.org/project/password-strength/ 包包含执行此操作的代码。如果您对如何完成而不是实际执行感兴趣,可以阅读源代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-24
        • 2014-12-20
        • 2017-07-08
        • 1970-01-01
        • 1970-01-01
        • 2016-04-12
        • 2017-06-16
        相关资源
        最近更新 更多