我想检查一个字符串是否只包含 A-Z 和 a-z 和 0-9 和下划线和破折号 (_ -)
任何其他特殊符号,如!"#\%,都不应包含在其中
我该如何编写正则表达式?
并使用match
或?
我的字符串看起来像这样:QOIWU_W QWLJ2-1
我想检查一个字符串是否只包含 A-Z 和 a-z 和 0-9 和下划线和破折号 (_ -)
任何其他特殊符号,如!"#\%,都不应包含在其中
我该如何编写正则表达式?
并使用match
或?
我的字符串看起来像这样:QOIWU_W QWLJ2-1
是的,re.match
看起来很合适(请原谅我的双关语)。至于正则表达式,可以考虑使用这样的内容:'[A-Za-z0-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. Barberimport re
if (re.match('^[a-zA-Z0-9-_]*$',testString)):
//successful match
不需要使用正则表达式。
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 Pihlimport re
re.search('[^a-zA-Z0-9-_]+', your_string) == None