在Python中检查字符串是否包含某些字符

5

我想检查一个字符串是否只包含 A-Z 和 a-z 和 0-9 和下划线和破折号 (_ -)

任何其他特殊符号,如!"#\%,都不应包含在其中

我该如何编写正则表达式?

并使用match或?

我的字符串看起来像这样:QOIWU_W QWLJ2-1

5个回答

9

是的,re.match 看起来很合适(请原谅我的双关语)。至于正则表达式,可以考虑使用这样的内容:'[A-Za-z0-9-_]*'


4
你也可以使用 [\w-] 替代 [A-Za-z0-9-_]。 - pcalcao

9

使用re不会有任何问题,但是出于科学好奇心,另一种不需要通过re的方法是使用集合:

>>> valid = set('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ ')
>>> def test(s):
...    return set(s).issubset(valid)
... 
>>> test('ThiS iS 4n example_sentence that should-pass')
True
>>> test('ThiS iS 4n example_sentence that should fail!!')
False

为了简洁,测试函数也可以这样写:
>>> def test(s):
...    return set(s) <= valid

编辑: 为了满足好奇心,以下是一些时间数据(以秒为单位,每个测试实现运行三组迭代):

>>> T(lambda : re.match(r'^[a-zA-Z0-9-_]*$', s)).repeat()
[1.8856699466705322, 1.8666279315948486, 1.8670001029968262]
>>> T(lambda : set(y) <= valid).repeat()
[3.595816135406494, 3.568570852279663, 3.564558982849121]
>>> T(lambda : all([c in valid for c in y])).repeat()
[6.224508047103882, 6.2116711139678955, 6.209425926208496]

你不需要使用 list 函数来获取字符集合。 - Michael J. Barber
@MichaelJ.Barber - 谢谢,已修复(并且从计时中减去了1秒...) - mac

1
你可以使用正则表达式模块。
import re
if (re.match('^[a-zA-Z0-9-_]*$',testString)):
    //successful match

那种语法是哪个版本的Python有的? - Some programmer dude
@Oliver 谢谢你,但我想在 PHP 中需要 ^ 和 $,而不是在 Python 中。 - manxing
2
@manxing 不完全正确。^ 和 $ 标记字符串的开头和结尾。 - Oliver

0

不需要使用正则表达式。

import string

# build a string containing all valid characters
match=string.ascii_letters + string.digits + '_' + '-' + ' '

In [25]: match
Out[25]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_- '

test='QOIWU_W QWLJ2-'

In [22]: all([c in match for c in test])
Out[22]: True

In [23]: test2='abc ;'

In [24]: all([c in match for c in test2])
Out[24]: False

in 的时间复杂度与搜索字符串的长度成线性关系,所以这并不是一个令人惊讶的结果。不过还是感谢提供基准测试! - Fredrik Pihl

-1
import re
re.search('[^a-zA-Z0-9-_]+', your_string) == None

如果re.search()遇到一个或多个非字母数字字符的实例,它将返回一个匹配对象;否则返回None。因此,您需要检查字符串是否安全。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接