python - 如何检查字符串是否包含多个正则表达式并捕获匹配的部分?

标签 python regex django-forms python-re

我想要什么

我正在使用 django 表单,它需要输入密码。我需要传递多个正则表达式的输入值,这将测试是否:

  • 至少有一个字符为小写
  • 至少有一个字符是大写
  • 至少有一个字符是数字
  • 至少有一个字符是特殊字符(符号)
  • 最少 8 个字符

我想知道这些条件中哪些已满足,哪些未满足。

我做了什么

def clean_password(self):
        password = self.cleaned_data.get("password")

        regexes = [
            "[a-z]",
            "[A-Z]",
            "[0-9]",
            #other regex...
        ]

        # Make a regex that matches if any of our regexes match.
        combined = "(" + ")|(".join(regexes) + ")"

        if not re.match(combined, password):
            print("Some regex matched!")
            
            # i need to pass in ValidationError those regex that haven't match
            raise forms.ValidationError('This password does not contain at least one number.')

最佳答案

虽然你可以在这里使用正则表达式,但我会坚持使用普通的Python:

from string import ascii_uppercase, ascii_lowercase, digits, punctuation
from pprint import pprint

character_classes = {'lowercase letter': ascii_lowercase,
                     'uppercase letter': ascii_uppercase,
                     'number': digits,
                     'special character': punctuation  # change this if your idea of "special" characters is different
                    }

minimum_length = 8

def check_password(password):
    long_enough = len(password) >= minimum_length
    if not long_enough:
        print(f'Your password needs to be at least {minimum_length} characters long!')
    result = [{class_name: char in char_class for class_name, char_class in character_classes.items()} for char in password]
    result_transposed = {class_name: [row[class_name] for row in result] for class_name in character_classes}
    for char_class, values in result_transposed.items():
        if not any(values):
            # Instead of a print, you should raise a ValidationError here
            print(f'Your password needs to have at least one {char_class}!')

    return result_transposed                      

check_password('12j3dSe')

输出:

Your password needs to be at least 8 characters long!
Your password needs to have at least one special character!

这允许您以更灵活的方式修改密码要求,并且万一您想说“您需要此字符类别的 X”...

关于python - 如何检查字符串是否包含多个正则表达式并捕获匹配的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55898925/

相关文章:

django - 将 mixin 与 Django 表单类一起使用

python - PyArg_ParseTupleAndKeywords 抛出警告 : ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

python - 最长回文子串自顶向下动态规划

python - Python 中列表的高级(可能)选择规则

c# - 如何匹配这个字符串使用正则表达式?

java - 正则表达式查找整个单词

regex - 正则表达式 ^(\d{1,2})$ 是什么意思?

python - 为什么带有 auto_now_add 的 DateTimeField 无法进入表单字段

django - 自定义表单作者 - 自动将作者保存到数据库

python - 使用 matplotlib 的大量子图