Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中只允许字符串中的数字、字母和某些字符?_Python_Regex - Fatal编程技术网

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

如何在Python中只允许字符串中的数字、字母和某些字符?,python,regex,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

我想做一个密码检查器,但如何做才能在存在除数字、大写/小写和(,)、$、%和./以外的字符时写入错误

到目前为止,我所拥有的:

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')
导入系统 进口稀土 导入字符串 随机输入 密码=输入(“输入密码:”) 长度=长度(密码) 如果长度小于8: 打印(“\n密码必须在8-24个字符之间\n\n”) elif长度>24: 打印(“\n密码必须在8-24个字符之间\n\n”) elif未重新匹配(“[a-z]”,密码): 打印('错误') 试试看

elif不重新匹配('^[a-zA-Z0-9()$%\uz/]*$,密码):


我不知道您是否允许使用逗号。如果是这样,请使用
^[a-zA-Z0-9()$%./,]*$

您需要有一个正则表达式来验证:

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

对于Python,当出现问题时,应该引发异常:

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

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

另一种解决方案是:

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

你是在问如何编写一个符合你设置的条件的正则表达式吗?这是一个非常有用的工具:你应该先学习正则表达式的基础知识。打开你最喜欢的搜索引擎,搜索类似“regex教程”的内容。这里有一个可能与你的问题相关的链接,当你不想使用regex时,这个链接非常好。谢谢