2017-10-17 77 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") 
相关问题