检查字符串是否包含python中的特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26130604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:07:43  来源:igfitidea点击:

check if string contains special characters in python

pythonregexpython-2.7

提问by mungaih pk

I want to check if a password contains special characters. I have googled for a few examples but cant find that addresses my problem. How do I do it? Here is how I am trying it so far;

我想检查密码是否包含特殊字符。我用谷歌搜索了几个例子,但找不到解决我的问题的方法。我该怎么做?到目前为止,这是我尝试的方式;

elif not re.match("^[~!@#$%^&*()_+{}":;']+$",password)
        print "Invalid entry."
        continue

My string is password.

我的字符串是密码。

回答by Silas Ray

You don't need a regex for this. Try:

您不需要为此使用正则表达式。尝试:

elif set('[~!@#$%^&*()_+{}":;\']+$').intersection(password):
    print "Invalid entry."

The quotation mark has been escaped in the string. What this does is create a set containing all your invalid characters, then take the intersection of it and password(in other words, a set containing all unique characters that exist in both the set and the password string). If there are no matches, the resulting set will be empty, and thus evaluate as False, otherwise it will evaluate as Trueand print the message.

引号已在字符串中转义。这样做是创建一个包含所有无效字符的集合,然后取它的交集password(换句话说,一个包含集合和密码字符串中存在的所有唯一字符的集合)。如果没有匹配项,结果集将为空,因此评估为False,否则将评估为True并打印消息。

回答by MattDMo

Several of the symbols in your special characters string have special meaning in regexes, and must be escaped. You are getting the syntax error because you included "in the middle of a string delineated by double quotes, so Python finishes processing the string there, then chokes on the garbage it sees afterwards. Try this:

特殊字符串中的几个符号在正则表达式中具有特殊含义,必须进行转义。您收到语法错误是因为您包含"在由双引号括起来的字符串的中间,因此 Python 在那里完成处理该字符串,然后在它之后看到的垃圾中窒息。尝试这个:

elif not re.match(r"[~\!@#$%\^&\*\(\)_\+{}\":;'\[\]]", password):
    print "Invalid entry"
    continue

I used a raw string literal, which you should always use in regexes. I escaped the characters that needed to be escaped, and simplified your expression a bit, as the beginning ^and end $of string markers aren't necessary - as soon as 1 match is made, it will return True, and will skip the following code.

我使用了原始字符串文字,您应该始终在正则表达式中使用它。我转义了需要转义的字符,并稍微简化了您的表达式,因为字符串标记的开头^和结尾$不是必需的 - 一旦进行了 1 个匹配,它将返回 True,并将跳过以下代码。

When in doubt, escape :)

如有疑问,请逃避:)