Advanced Password Validation with Regex

Using regular expressions to validate passwords based on complex criteria

Python
import re

def validate_password(password):
    # At least 8 characters long
    # Contains at least one uppercase letter, one lowercase letter, one digit, and one special character
    # Does not contain three consecutive identical characters
    pattern = r'^(?!.*(\w)\1{2,})(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*()_+{}\[\]:;<>,.?~\\/-]).{8,}$'
    return re.match(pattern, password) is not None

def password_strength(password):
    strength = 0
    checks = [
        (r'.{8,}', "Length of at least 8 characters"),
        (r'.*[A-Z].*', "Contains uppercase letter"),
        (r'.*[a-z].*', "Contains lowercase letter"),
        (r'.*\d.*', "Contains digit"),
        (r'.*[!@#$%^&*()_+{}\[\]:;<>,.?~\\/-].*', "Contains special character"),
        (r'^(?!.*(\w)\1{2,}).*$', "No three consecutive identical characters")
    ]
    
    for pattern, description in checks:
        if re.match(pattern, password):
            strength += 1
            print(f"✓ {description}")
        else:
            print(f"✗ {description}")
    
    return strength

passwords = ["Weak123!", "StrongP@ssw0rd", "aaa123ABC!", "Short1!", "NoDigitXYZ!"]
for password in passwords:
    print(f"\nPassword: {password}")
    if validate_password(password):
        print("Valid password")
    else:
        print("Invalid password")
    strength = password_strength(password)
    print(f"Strength: {strength}/6")
Click Run or press shift + ENTER to run code.