SoFunction
Updated on 2025-03-03

Use regular expressions to determine the password strength

I learned the Python Re template and wrote an article and found that no one reads it. So I summarized the experience, no one loved the theory, and the hearts of practical people. Since no one likes theory, I will go directly to actual combat and refine the theory in actual combat. Without further ado, just upload the code first

def password_level(password):
 weak = (r'^((\d+)|([A-Za-z]+)|(\W+))$')
 level_weak = (password)
 level_middle = (r'([0-9]+(\W+|\_+|[A-Za-z]+))+|([A-Za-z]+(\W+|\_+|\d+))+|((\W+|\_+)+(\d+|\w+))+',password)
 level_strong = (r'(\w+|\W+)+',password)
 if level_weak:
  print 'password level is weak',level_weak.group()
 else:
  if (level_middle and len(level_middle.group())==len(password)):
   print 'password level is middle',level_middle.group()
  else:
   if level_strong and len(level_strong.group())==len(password):
    print 'password level is strong',level_strong.group()

Explain it

Weak password: all numbers, symbols, letters

Medium password: numbers plus symbols, numbers plus letters, letters plus symbols

Strong password: three mixed.

I don't have case sensitivity, and I hope those who are interested can write it themselves. The problem occurs on \w because \w is equivalent to [A-Za-z0-9_], so the previous pass \W cannot match the string containing the sliding line.

Let's take a look at the medium password. The number plus symbols or letters or _ is a group. The letter plus symbols or underscores or symbols is a group. The symbols or underscores plus letters or numbers are a group. I always feel that the code inside this seems to be wrong, but I didn't find anything wrong after testing. Let's use this version 0.0.1 first.

Test code

if __name__ == '__main__':
 passwords = ('11','aa','LL','1a','1_','a_','a1','_1','*a','1a_','1a<')
 for pw in passwords:
  password_level(pw)
'''----------------------output------------------------
#password level is weak 11
#password level is weak aa
#password level is weak LL
#password level is middle 1a
#password level is middle 1_
#password level is middle a_
#password level is middle a1
#password level is middle _1
#password level is middle *a
#password level is strong 1a_
#password level is strong 1a<
'''

The above is the example code introduced by the editor to use regular expressions to determine the strength of the password. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!