2017-10-17 73 views
-1

我想創建一個密碼檢查器,但是如何創建它,以便在數字,大寫/小寫和(,),$,%,_ /以外的其他字符時可以寫入錯誤。如何只允許Python中的字符串中的數字,字母和某些字符?

我有什麼至今:

import sys 
import re 
import string 
import random 

password = input("Enter Password: ") 
length = len(password) 
if length < 8: 
    print("\nPasswords must be between 8-24 characters\n\n") 
elif length > 24: 
    print ("\nPasswords must be between 8-24 characters\n\n") 

elif not re.match('[a-z]',password): 
     print ('error') 
+2

https://regexone.com/ –

+0

你問如何編寫符合您設置的條件的正則表達式? – thumbtackthief

+1

這是一個非常有用的工具:https://regex101.com/ – thumbtackthief

回答

0

嘗試

elif not re.match('^[a-zA-Z0-9()$%_/.]*$',password):

,如果你想允許逗號我不能告訴。如果是使用^[a-zA-Z0-9()$%_/.,]*$

0

你需要有一個正則表達式對你將驗證:

m = re.compile(r'[a-zA-Z0-9()$%_/.]*$') 
if(m.match(input_string)): 
    Do something.. 
else 
    Reject with your logic ... 
0

使用Python,你應該引發異常時出現錯誤:

if re.search(r'[^a-zA-Z0-9()$%_]', password): 
    raise Exception('Valid passwords include ...(whatever)') 

此搜索對於在方括號之間定義的字符集中不是(^)的密碼中的任何字符。

0

另一個解決辦法是:

allowed_characters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','0','(',')','$','%','_','/'] 

password=input("enter password: ") 
if any(x not in allowed_characters for x in password): 
    print("error: invalid character") 
else: 
    print("no error") 
相關問題