0
#! python
#STRONG PASSWORD PROGRAM
import re, pyperclip


pw_compare_lower=re.compile(r'[a-z]')
pw_compare_upper=re.compile(r'[A-Z]')
pw_compare_digit=re.compile(r'[0-9]')
gr=str(input())
def Checker(gr):
    if len(gr)<8:
        return 0
    if pw_compare_lower.search(gr)==None:
        return 0
    if pw_compare_upper.search(gr)==None:
        return 0
    if pw_compare_digit.search(gr)==None:
        return 0
    return 1
if (Checker(gr))==1:
    print("Strong Password")
elif (Checker(gr))==0:
    print("Weak Password")

Is there a way I can write the three pw_compare_digit, pw_compare_upper, pw_compare_lower functions in one line to form a single regex.

The conditions are as below:

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

2 Answers2

2

Yes, with lookaheads

^(?=[^a-z\n]*[a-z])(?=[^A-Z\n]*[A-Z])(?=[^\d]*\d).{8,}$

See a demo on regex101.com.


All of your code can then be shortened to
import re, pyperclip

rx = re.compile(r'^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z]).{8,}$')
if rx.match(your_string_here):
    # pass
Jan
  • 42,290
  • 8
  • 54
  • 79
1

I want to note that you can achieve this also without regular expression, following code will check if gr is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit:

def Checker(gr):
    return len(gr)>=8 and any([i.islower() for i in gr]) and any([i.isupper() for i in gr]) and any([i.isdigit() for i in gr])

Note that this return True or False, if you want rather 0 or 1 simply put whole returned value into int().

Daweo
  • 31,313
  • 3
  • 12
  • 25