書中7.18的強口令實踐題python
寫一個函數,它使用正則表達式,確保傳入的口令字符串是強口令。強口令的定義是:正則表達式
長度很多於8 個字符,同時包含大寫和小寫字符,至少有一位數字。函數
你可能須要用多個正則表達式來測試該字符串,以保證它的強度。測試
推薦寫法1更接近書中多個正則的含義也更好理解,寫法2參考網上零寬斷言。spa
注意寫法1的大小寫匹配要分開,若是寫爲[a-zA-Z]則只會匹配大小寫字符之一便可,不知足同時有大小寫code
1 #! python3 2 # 7.18.1 強口令的定義是:長度很多於8 個字符,同時包含大寫和小寫字符,至少有一位數字。 3 #你可能須要用多個正則表達式來測試該字符串,以保證它的強度。 4 5 import re 6 passwd=str(input('enter a passwd: ')) 7 re1=re.compile(r'.{8,}') 8 re2=re.compile(r'[a-z]') 9 re3=re.compile(r'\d+') 10 re4=re.compile(r'[A-Z]') 11 12 #寫法2 13 #re9=re.compile(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$') 14 15 if re1.search(passwd) and re2.search(passwd) and re3.search(passwd) and re4.search(passwd): 16 #if re9.search(passwd): 17 print('passwd is strong enough') 18 else: 19 print('passwd need upper,lower,number and more than 8')