1

I'm now working on the practice projects in this book and would like to get some advice on the project below to know if I'm on track.


Write a function that uses regular expressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.


I came up with the below but not quite sure where to go from here. Appreciate if anyone could help! Thanks in advance!


#! /usr/bin/env python3
#chapter_7.py - Detects strong passwords.

import pyperclip, re

strong_pwd_regex = re.compile(r'(A-Za-z)(0-9)+{8,}')

password = str(pyperclip())
matches = []

for groups in strong_pwd_regex.findall(password):
    if len(matches) < 8:
        print('Password needs to be at least 8 characters long.')
L.C
  • 11
  • 1
  • 4

1 Answers1

1

You can use this regex:

^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$

This regex will enforce these rules:

  • At least one upper case English letter, (?=.*?[A-Z])
  • At least one lower case English letter, (?=.*?[a-z])
  • At least one digit, (?=.*?[0-9])
  • At least one special character, (?=.*?[#?!@$%^&*-])
  • Minimum eight in length .{8,} (with the anchors)
Vladyslav
  • 2,018
  • 4
  • 18
  • 44
  • so I checked on `?=.*?` and it says the `.` is unrelated to the `(?=`. Regex starts with `(?=` ensures that you can see, but don't consume followed by `.*` which is zero or more of any character. Is that right? Any comments on the codes after that? – L.C Jul 21 '17 at 09:21
  • This seems overly complicated to me. However, it is still useful for learning regexes. My answer to the project was much simpler. – Jacob Helfman May 23 '20 at 21:16