[英]How to check if a string contains only specific characters in python?
I want my string only have (a-zA-Z0-9@.-_) but when using this code:我希望我的字符串只有 (a-zA-Z0-9@.-_) 但是在使用此代码时:
import re
e='p12/5@gmail.com'
p=re.compile(r'[a-zA-Z0-9@.-_]')
for ele in e:
if bool(p.search(ele)):
print('okay')
else:
print('n')
it prints 'okay' but I expect to print 'n' because my string(e) contains '/' and I didn't declare it on my regex.它打印'okay',但我希望打印'n',因为我的字符串(e)包含'/'并且我没有在我的正则表达式中声明它。 what should I do?我应该怎么办? I also used re.match
and didn't help me either.我也使用re.match
并没有帮助我。
There are a couple of issues here.这里有几个问题。 First .
首先.
and -
are meta-characters, and need to escaped with a \
.和-
是元字符,需要用\
转义。 Second, you don't really need the loop here - add a *
to indicate any number of these characters, and qualify the regex between ^
and $
to signify the entire string needs to be made up of these characters:其次,您实际上并不需要此处的循环 - 添加*
来表示任意数量的这些字符,并限定^
和$
之间的正则表达式以表示整个字符串需要由这些字符组成:
import re
e = 'p12/5@gmail.com'
p = re.compile(r'^[a-zA-Z0-9@\.\-_]*$')
if p.match(e):
print('okay')
else:
print('n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.