![](/img/trans.png)
[英]How do I verify that a string only contains letters, numbers, underscores and dashes?
[英]How do I check if a string only contains alphanumeric characters and dashes?
我正在测试的字符串可以与[\\w-]+
匹配。 我可以测试一个字符串是否符合Python中的这个,而不是有一个不允许的字符列表并测试它?
如果要针对正则表达式测试字符串,请使用re库
import re
valid = re.match('^[\w-]+$', str) is not None
Python也有正则表达式:
import re
if re.match('^[\w-]+$', s):
...
或者您可以创建允许的字符列表:
from string import ascii_letters
if all(c in ascii_letters+'-' for c in s):
...
不使用纯python导入任何模块,删除任何无alpha,数字除了破折号。
string = '#Remove-*crap?-from-this-STRING-123$%'
filter_char = lambda char: char.isalnum() or char == '-'
filter(filter_char, string)
# This returns--> 'Remove-crap-from-this-STRING-123'
或者在一行中:
''.join([c for c in string if c.isalnum() or c in ['-']])
为了测试字符串是否只包含字母数字和破折号,我会使用
import re
found_s = re.findall('^[\w-]+$', s)
valid = bool(found_s) and found_s[0] == s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.