首页 > 解决方案 > 编写必须满足某些要求的正则表达式,而不考虑特定符号的顺序

问题描述

我正在编写一个程序,该程序根据输入密码的强度返回特定消息。为了被标记为“强”,它必须满足某些要求,我将在下面的程序文档中列出:

#! python3
# strongPassword.py

# Strong Password Detection
# Write a function that uses regular expressions to make sure
# the password string it is passed is strong. A strong password
# is defined as one that is at least eight characters long,
# contains both uppercase and lowercase characters, and has
# at least one digit. You may need to test the string against
# multiple regex patterns to validate its strength.

import pyperclip, re

passwordRegex = re.compile(r'''(
    ^(?=.*[A-Z].*[A-Z])                # at least two capital letters
    (?=.*[!@#$&*])                     # at least one of these special characters
    (?=.*[0-9].*[0-9])                 # at least two numeric digits
    (?=.*[a-z].*[a-z].*[a-z])          # at least three lower case letters
    .{10,}                              # at least 10 total digits
    $
    )''', re.VERBOSE)

def userInputPasswordCheck():
    ppass = input("Enter a potential password: ")
    mo = passwordRegex.search(ppass)
    if (not mo):
        print("Not strong, bling blong")
        return False
    else:
        print("Long, Strong, and down to get the crypto on")
        return True


userInputPasswordCheck()  

我在 Github 上找到了这段代码,但我不太明白它是如何设法创建一个没有按顺序列出模式的某些部分的正则表达式。

我的具体问题是,我如何能够以更“模糊”的方式编写正则表达式(仅提及要求,例如最小 x 大写字符数、y 小写字符数和 z 位数,而没有突出显示每个部分必须出现的顺序)。

这个特定的代码似乎使用''?='',我不完全理解(前瞻断言,只有在字符串的另一个特定部分之后才匹配字符串的特定部分,我知道,我只是不'不了解它在此特定代码中的使用方式)。

我将不胜感激任何帮助。

提前致谢。

标签: pythonregex

解决方案


方法如下:

from re import search

def userInputPasswordCheck():
    pas = input('Input your password: ')
    if all([len(pas) > 7, search('[0-9]', pas), search('[a-z]', pas), search('[A-Z]',pas)]):
        print("Long, Strong, and down to get the crypto on")
        return True
    else:
        print("Not strong, bling blong")
        return False

userInputPasswordCheck()  

输出:

Input your password: Hello101
Long, Strong, and down to get the crypto on

推荐阅读