題目:
寫一個函數,它使用正則表達式,確保傳入的口令字符串是強口令。強口令的定義是:長度不少於 8 個字符,同時包含大寫和小寫字符,至少有一位數字。你可能需要用多個正則表達式來測試該字符串,以保證它的強度。
分析:
這題很簡單,就是用正則表達式檢測是否一個以上數字,有大寫和小寫字母。
代碼:
import re
text = str(input('輸入一串口令:'))
def checkpw(text):
flag = True
if len(text) < 8:
flag = False
chpw1 = re.compile(r'[a-z]').search(text)
chpw2 = re.compile(r'[0-9]+').search(text)
chpw3 = re.compile(r'[A-Z]').search(text)
if (chpw1 == None) or (chpw2 == None) or (chpw3 == None):
flag = False
if flag:
print("口令正確")
else:
print("口令錯誤")
checkpw(text)
運行結果:
輸入一串口令:dsaf888DFDHSG
口令正確
輸入一串口令:sdaf33
口令錯誤