决赛(?)
答案,包装在函数中,带有注释的交互式会话:
>>> import re>>> def special_match(strg, search=re.compile(r'[^a-z0-9.]').search):... return not bool(search(strg))...>>> special_match("")True>>> special_match("az09.")True>>> special_match("az09.n")False# The above test case is to catch out any attempt to use re.match()# with a `$` instead of `Z` -- see point (6) below.>>> special_match("az09.#")False>>> special_match("az09.X")False>>>
注意:在此答案中还有一个比较与使用re.match()的比较。进一步的计时表明,match()将以更长的字符串获胜;当最终答案为True时,match()的开销似乎比search()大得多。这令人费解(也许这是返回MatchObject而不是None的代价),并且可能需要进行进一步的反复讨论。
==== Earlier text ====
[以前]接受的答案可以使用一些改进:
(1)Presentation看起来像是一个交互式Python会话的结果:
reg=re.compile('^[a-z0-9.]+$')>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')True
但是match()不返回
True
(2)与match()
^一起使用时,模式开头的冗余,并且看起来比没有模式的相同模式稍慢
^
(3)对于任何re模式,应该不加思索地自动使用原始字符串
(4)点号/句点前面的反斜杠是多余的
(5) 比OP的代码慢!
prompt>rem OP's version -- NOTE: OP used raw string!prompt>python26python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';importre;reg=re.compile(r'[^a-z0-9.]')" "not bool(reg.search(t))"1000000 loops, best of 3: 1.43 usec per loopprompt>rem OP's version w/o backslashprompt>python26python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';importre;reg=re.compile(r'[^a-z0-9.]')" "not bool(reg.search(t))"1000000 loops, best of 3: 1.44 usec per loopprompt>rem cleaned-up version of accepted answerprompt>python26python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';importre;reg=re.compile(r'[a-z0-9.]+Z')" "bool(reg.match(t))"100000 loops, best of 3: 2.07 usec per loopprompt>rem accepted answerprompt>python26python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';importre;reg=re.compile('^[a-z0-9.]+$')" "bool(reg.match(t))"100000 loops, best of 3: 2.08 usec per loop
(6)会 产生错误的答案!!
>>> import re>>> bool(re.compile('^[a-z0-9.]+$').match('1234n'))True # uh-oh>>> bool(re.compile('^[a-z0-9.]+Z').match('1234n'))False
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)