24

我正在测试的字符串可以与[\w-]+. 我可以在 Python 中测试一个字符串是否符合这一点,而不是列出不允许的字符并对其进行测试吗?

4

4 回答 4

38

如果要针对正则表达式测试字符串,请使用re

import re
valid = re.match('^[\w-]+$', str) is not None
于 2012-06-08T07:10:39.900 回答
8

Python 也有正则表达式:

import re
if re.match('^[\w-]+$', s):
    ...

或者您可以创建一个允许的字符列表:

from string import ascii_letters
if all(c in ascii_letters+'-' for c in s):
    ...
于 2012-06-08T07:11:03.367 回答
6

在不使用纯 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'

或者在一行中:

''.join([c for c in string if c.isalnum() or c in ['-']])
于 2017-11-27T09:11:15.520 回答
1

要测试字符串是否包含字母数字和破折号,我会使用

import re
found_s = re.findall('^[\w-]+$', s)
valid = bool(found_s) and found_s[0] == s
于 2012-10-09T19:24:32.140 回答