【问题标题】:Strong Password Detection regex强密码检测正则表达式
【发布时间】:2021-01-30 08:43:47
【问题描述】:
#!/usr/bin/env python3

import re

passRegex = re.compile(r'''(
        .{8,}                     # 8 or more characters
        [A-Z]                     # at least 1 A-Z char
        [a-z]                     # at least 1 a-z char
        [0-9]                     # at least 1 0-9 number
        )''', re.VERBOSE)

    
def strong_password():
    password = input("Enter a password: ")
    match = passRegex.search(password)
    if (not match):
        print("Password not strong enough")
        return False
    else:
        print("Password is strong")
        return True

strong_password()

这是来自第 7 章用 python 自动化无聊的东西。有人可以解释我做错了什么吗?由于某种原因,我的正则表达式无法按预期工作。

这是完整的问题:编写一个使用正则表达式的函数,以确保它传递的密码字符串是强密码。一个强壮的 密码被定义为至少八个字符长的密码,包含大写和小写 字符,并且至少有一位数字。您可能需要针对多个正则表达式模式测试字符串以 验证它的实力。

【问题讨论】:

  • “按预期”,也许可以按照您的意愿放置一些输入/输出示例,并解释您的代码在哪个输入上产生了错误的输出?顺便说一句,if not b then else 相当于 if b else then
  • 对不起。这是一个示例: $ python3 strongPassword.py 输入密码:qweQWE123 密码不够强。我希望这是一个强密码。

标签: python-3.x


【解决方案1】:

您打算断言一系列密码要求,但您当前的正则表达式实际上并未做出这些断言。一种方法是为每个需求添加一个积极的前瞻:

passRegex = re.compile(r'^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$', re.VERBOSE)

【讨论】:

  • 这是为什么呢?当我使用 upper = re.compile[A-Z] lower = re.compile[a-z] 等单独传递这些时,它可以工作。
【解决方案2】:

尝试将您的正则表达式对象放入您违抗的函数中。并将密码(输入)传递给您的函数。

在这里,我为我做的

import re  

# create a function isPasswordStrong 
def isStrongPass(password):
# create the Regex object from re.compile
    passwordRegex = re.compile(r"""
         (?=.*[a-z])   # matching with char a to z (0 or more)
         (?=.*[A-Z])   # matching with char A to Z (0 or more)
         (?=.*[0-9])   # matching with digit from 0-9
         .{8,}        # must have at least 8 or more
          """, re.VERBOSE)
     passEvaluation = passwordRegex.search(password)
     if passEvaluation != None:  # if it is matched
         return True # Return this 

print('Enter your password: ')
password = input()

test = isStrongPass(password)
if test == True:
     print('Your password is STRONG')
else:
     print('Weak password')

【讨论】:

    【解决方案3】:

    @Tim 的回答在显示正则表达式按预期工作方面做得很好,这个答案将特别突出为什么您当前的模式没有。

    正则表达式对排序非常具体。 让我们来看看你的正则表达式。

    .{8,} 匹配任意字符最多 8 次。

    [A-Z] 之后,查找单个大写字母。

    [a-z] 之后,查找单个小写字母。

    [0-9] 之后,查找一个 0-9 整数。

    排序很重要。您的正则表达式唯一匹配的就是这样的密码:

    1234AbCdAa8

    8 个或更多任意字符,后跟一个大写字母,然后是一个小写字母,然后是一个数字。任何与该模式不匹配的字符串都不会在您的正则表达式中注册为匹配项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-16
      • 2010-11-12
      • 1970-01-01
      • 2018-08-17
      • 2016-12-17
      相关资源
      最近更新 更多