如何只允许Python中的字符串中的数字,字母和某些字符?

时间:2017-10-17 20:26:24

标签: python regex

我想制作一个密码检查器,但是我该如何制作呢?如果有除数字,大写/小写和(,),$,%,_ /之外的字符,我可以写错误。

到目前为止我所拥有的:

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')

4 个答案:

答案 0 :(得分:1)

您需要有一个正则表达式,您将对其进行验证:

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

答案 1 :(得分:0)

尝试

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

我不知道你是否想要逗号。如果是,请使用^[a-zA-Z0-9()$%_/.,]*$

答案 2 :(得分:0)

使用Python,你应该在出现问题时提出异常:

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

这将在方括号之间定义的字符集中搜索密码中不是(^)的任何字符。

答案 3 :(得分: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")