如何检查字符串是否具有多个正则表达式并捕获匹配的部分? [英] how to check if a string fullfil with multiple regex and capture that portion that match?

查看:32
本文介绍了如何检查字符串是否具有多个正则表达式并捕获匹配的部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的

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

I'm working with a django form and it takes a password input. I need to pass the input value for multiple regexes, which will test if:

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

我想知道这些条件中哪些满足,哪些不满足.

And I would like to know which of these conditions were fulfilled and which were not.

我做了什么

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:

While you can use a regex here, I would stick to normal 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 个"...

This allows you to modify the password requirements in a more flexible fashion, and in case you ever want to say "you need X of this character class"...

这篇关于如何检查字符串是否具有多个正则表达式并捕获匹配的部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆