使用正则表达式,如何匹配密码中任意位置的特殊字符和数字?

Using regex, how to match special chars and numbers anywhere in a password?

唯一匹配的特殊字符位置是密码的末尾。如果特殊字符位于开头或末尾以外的任何位置,它将无法匹配并拒绝密码。

import re

while True:
    password = input("Please enter a password containing at least 6 letters, \n "
                "one number, one capital letter, and at least one special character. ")

    pattern = r"[A-Z]+?[A-Za-z]{6,}?[0-9]+?[^a-zA-Z0-9]+?"

    if not re.search(pattern, password):
        print("Please try again")

    else:
        print("Your new password is: ", password)
        break

我愿意接受包含特殊字符和数字的密码,而不仅仅是在末尾,例如

我已经尝试使用其他答案中建议的正则表达式代码,但到目前为止 none 它们适用于我的场景。

尝试在您的密码正则表达式模式中使用前瞻:

pattern = r'^(?=.*[0-9])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{6,}$'
if not re.search(pattern, password):
    print("Please try again")

这里是正则表达式模式的简要说明:

^                        from the start of the password
    (?=.*[0-9])          assert that at least one digit is present
    (?=.*[A-Z])          assert that at least one capital letter is present
    (?=.*[^a-zA-Z0-9])   assert one special character
    .{6,}                then match any 6 or more characters
$                        end of the password

这可以通过前瞻来完成。可以通过这种方式先行检查每个标准:

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

除了 re.search 之外,您还可以使用 re.matchre.fullmatch 作为验证器。

可以使用 lookbehinds 获得等效表达式:

.*(?<=.*[A-Z])(?<=(?:.*[A-Za-z]){6,})(?<=(?:.*[0-9]))(?<=(?:.*[^a-zA-Z0-9]))

您甚至可以混合搭配,例如:

(?=.*[A-Z])(?=(?:.*[A-Za-z]){6,}).*(?<=(?:.*[0-9]))(?<=(?:.*[^a-zA-Z0-9]))

在功能上,这些方法都是等效的。差异主要是美学上的,尽管当然也可能存在导致小的时间差异的实现细节。