用正则表达式检查密码的强度

时间:2017-11-23 07:03:52

标签: python regex

该功能是找出密码的强度。如果:

,它被认为是强大的
  1. 长度大于或等于10个字符
  2. 它至少包含一位数字
  3. 至少一个大写字母
  4. 一个小写字母
  5. 密码只能包含ASCII拉丁字母或数字
  6. 有没有办法减少函数中的代码量? 请帮我制作短于200个字符的功能代码(尝试解决而不为变量赋值)

    import re
    def golf(password):
        if len(password) >=  10 \
        and re.search("^[a-zA-Z0-9]+", password) \
        and re.search("[a-z]+", password) \
        and re.search("[A-Z]+", password) \
        and re.search("[0-9]+", password):
            print(password, True)
            return True
        else:
            print(password, False)
            return False
    
    
    if __name__ == '__main__':
        golf('A1213pokl') == False
        golf('bAse730onE') == True
        golf('asasasasasasasaas') == False
        golf('QWERTYqwerty') == False
        golf('123456123456') == False
        golf('QwErTy911poqqqq') == True
        golf('..........') == False
    

4 个答案:

答案 0 :(得分:3)

虽然您已经有了答案,但我甚至尝试优化模式。而不是.*然后回溯,我直接应用对比原理

(?=\D*\d)          # NOT a number, 0+ times, then one number
(?=[^A-Z]*[A-Z])   # NOT an UPPERCASE, 0+times, then an UPPERCASE
(?=[^a-z]*[a-z])   # same with lowercase
^[A-Za-z0-9]{10,}$ # allowed characters, 10+, with anchors on both sides

简化和demo

(?=\D*\d)(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])[A-Za-z0-9]{10,}$

这里的想法是,虽然.*让你走下线然后回溯,但上面的模式很可能会更快结束。

<小时/> 最后是Python代码段:

import re

def golf(password=None):
    rx = re.compile(r'(?=\D*\d)(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])[A-Za-z0-9]{10,}$')
    return True if rx.match(password) else False

passwords = ['A1213pokl', 'bAse730onE', 'asasasasasasasaas', 'QWERTYqwerty', '123456123456', 'QwErTy911poqqqq', '..........']
vectors = [golf(password) for password in passwords]
print(vectors)
# [False, True, False, False, False, True, False]

答案 1 :(得分:2)

(不是那么:)愚蠢的方式:

from re import search as s
def golf(p):
    return all([len(p)>=10,s("^[a-zA-Z0-9]+",p),s("[a-z]+",p),s("[A-Z]+",p),s("[0-9]+",p)])

顺便说一下,你可能想在assert块中发表一些if __name__ == '__main__':个陈述......

答案 2 :(得分:1)

这个正则表达式应该这样做:

 (?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])^[a-zA-Z0-9]{10,}$

答案 3 :(得分:0)

您可以使用一个正则表达式来检查密码强度。

^(?=(.*\d){2})(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z\d]).{10,}$

它将验证您的所有案例。

import re
def golf(password):
    if re.search("^(?=(.*\d){2})(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z\d]).{,}$", password):
        print(password, True)
        return True
    else:
        print(password, False)
        return False