简体   繁体   English

如何检查字符串是否仅包含 python 中的特定字符?

[英]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.

相关问题 如果字符串包含只包含特定代码页的字符,如何检查python? - how to check in python if a string contains characters only form specific code page? 如何检查字符串是否包含 Python 列表中的特定字符? - How to check if a string contains specific characters in a list in Python? 如何检查字符串是否只包含python中给定集合的字符 - How to check if a string contains only characters from a given set in python 在 Python 中,如何检查字符串是否只包含某些字符? - In Python, how to check if a string only contains certain characters? 如何在Python中提取包含特定字符的字符串 - How to extract string that contains specific characters in Python 检查字符串何时只包含python中的特殊字符 - Check when string contains only special characters in python 如何在 python 中检查字符串是否包含特定字符 - How to check if a string contains a specific character or not in python 如何在Python中检查列表是否包含特定字符串 - how to check if a list contains a specific string or not in python 如何检查字符串是否仅包含字母数字字符和短划线? - How do I check if a string only contains alphanumeric characters and dashes? 如何检查字符串是否仅包含不可打印的字符和空格? - How to check if string contains only unprintable characters and spaces?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM