Skip to content Skip to sidebar Skip to footer

How To Check If A String Fullfil With Multiple Regex And Capture That Portion That Match?

What I want 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: at least one character is a lowe

Solution 1:

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 = 8defcheck_password(password):
    long_enough = len(password) >= minimum_length
    ifnot long_enough:
        print(f'Your password needs to be at least {minimum_length} characters long!')
    result = [{class_name: char in char_classfor class_name, char_classin 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():
        ifnotany(values):
            # Instead of a print, you should raise a ValidationError hereprint(f'Your password needs to have at least one {char_class}!')

    return result_transposed                      

check_password('12j3dSe')

Output:

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

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"...

Post a Comment for "How To Check If A String Fullfil With Multiple Regex And Capture That Portion That Match?"