Learn Regular Expressions by Building a Password Generator

I’ve completed this module but I’m failing to understand something pretty basic I think.
Could anyone enlighten me please?

Specifically, in the if statement below #Check constraints, I get that len(re.findall(pattern, password) is the number of matches found for each pattern, in the password string.
How is this comparison working against constraint though? What does constraint equate to in each case?

Also, in functional terms, is the if statement checking that the password contains at least one of each pattern?

I’ve spoilered for anyone who’s not completed this module yet.

 while True:
    password = ''
    # Generate password
    for _ in range(length):
        password += secrets.choice(all_characters)
    constraints = [
        (nums, r'\d'),
        (special_chars, fr'[{symbols}]'),
        (uppercase, r'[A-Z]'),
        (lowercase, r'[a-z]')

    # Check constraints        
    if all(
        constraint <= len(re.findall(pattern, password))
        for constraint, pattern in constraints

constraint is a number, the value comes from the first element of each tuple, which comes from the function parameters.
So for example

for this tuple you are checking how many times \d is matched, and if that happens at least nums times


Doh, of course! Such a simple thing to miss. Makes perfect sense now, thanks!

1 Like