检查字符串是否包含python中的某些字符

时间:2011-12-07 15:05:53

标签: python

我想检查字符串是否只包含A-Z和a-z以及0-9和下划线和短划线(_ - )

任何其他特殊标志,如!“#%不应包含

如何编写正则表达式?

并使用match或?

我的字符串如下所示:QOIWU_W QWLJ2-1

5 个答案:

答案 0 :(得分:8)

是的,re.match似乎是一个很好的匹配(原谅双关语)。至于正则表达式,如下所示:'[A-Za-z0-9-_]*'

答案 1 :(得分:7)

使用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]

答案 2 :(得分:1)

您可以使用正则表达式模块。

import re
if (re.match('^[a-zA-Z0-9-_]*$',testString)):
    //successful match

答案 3 :(得分: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

答案 4 :(得分:-1)

import re
re.search('[^a-zA-Z0-9-_]+', your_string) == None
如果遇到一个或多个非字母数字字符的任何实例,则re.search()将返回匹配对象,否则返回None。所以你要检查字符串是否安全。

相关问题