Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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,我正在为一个项目的电子邮件制作一个验证程序 email = input("Enter an email address: ") if re.match("[~!#$%^&*()_+{}:;\']+$", email): print("Test 7 - Failed! The email has invalid characters!") test7 = "failed" else: print("Test 7 - Pass

我正在为一个项目的电子邮件制作一个验证程序

  email = input("Enter an email address: ")

  if re.match("[~!#$%^&*()_+{}:;\']+$", email):
        print("Test 7 - Failed! The email has invalid characters!")
        test7 = "failed"
    else:
        print("Test 7 - Passed! The email has no invalid characters!")
        test7 = "passed"
如果我输入像anyemail()@gmail.com这样的内容,它仍然会说它是有效的?我知道这一定是比赛的问题,但是有人能解释一下这个问题吗

我还尝试使用列表和find命令来查找特定的无效字符

您正在检查整个字符串是否由特殊字符组成(因为
re.match
正在字符串开头搜索模式匹配,并且您的模式末尾有
$
字符串结束锚)

删除
+$
并使用
re.search
检查字符串(电子邮件)是否至少包含一个特殊字符


请参见

除了Stribizev建议的原因之外,其中一些字符在正则表达式中使用时具有含义,这意味着您需要使用反斜杠对其进行转义(例如,根据上述正则表达式,您的电子邮件中是否允许使用反斜杠有点难说)

如果您只是在寻找无效字符,那么在没有正则表达式的情况下查找就容易多了。例如,您可以这样做:

invalid_chars = r"\~!#$%^&*()_+{}:;"
for char in email:
    if char in invalid_chars:
        # fail the test
        pass

但是,我建议为此使用一个字符白名单。那里有很多奇怪的字符。

一句忠告:不要试图验证电子邮件。这太难了,不值得花时间去尝试。我肯定有一个API或模块可以帮你做到这一点,比如:嘿,伙计们,谢谢你们的好话,但这是我计算机科学项目的一部分。我知道该模块,但遗憾的是,我必须手动完成PIf如果您想禁止反斜杠,请使用双反斜杠,因为单个反斜杠在正则表达式中被解释为“转义”,这意味着将下一个字符解释为文字而不是潜在的正则表达式字符(例如,如果未正确转义,通常会结束字符类)。谢谢。如果我决定完全从项目中去掉正则表达式,我可能会这样做。
invalid_chars = r"\~!#$%^&*()_+{}:;"
for char in email:
    if char in invalid_chars:
        # fail the test
        pass