q3d*_*q3d 22 python regex string alphanumeric
我正在测试的字符串可以匹配[\w-]+.我可以测试一个字符串是否符合Python中的这个,而不是有一个不允许的字符列表并测试它?
mat*_*ath 32
如果要针对正则表达式测试字符串,请使用re库
import re
valid = re.match('^[\w-]+$', str) is not None
Run Code Online (Sandbox Code Playgroud)
Python也有正则表达式:
import re
if re.match('^[\w-]+$', s):
...
Run Code Online (Sandbox Code Playgroud)
或者您可以创建允许的字符列表:
from string import ascii_letters
if all(c in ascii_letters+'-' for c in s):
...
Run Code Online (Sandbox Code Playgroud)
仅使用纯 python 不导入任何模块,删除除破折号外的任何非字母、数字。
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'
Run Code Online (Sandbox Code Playgroud)
或者在一行中:
''.join([c for c in string if c.isalnum() or c in ['-']])
Run Code Online (Sandbox Code Playgroud)