我在Windows总线中运行python2.7中的Idle下面的搜索。64位环境。
根据RegexBuddy的说法,搜索模式('patternalphaonly')不应该与一串数字产生匹配。在
我看着”http://docs.python.org/howto/regex.html“,但在那里没有看到任何可以解释为什么搜索和匹配似乎成功地找到了与模式匹配的东西。在
有没有人知道我做错了什么,或者误解了什么?在
>>> import re
>>> numberstring = '3534543234543'
>>> patternalphaonly = re.compile('[a-zA-Z]*')
>>> result = patternalphaonly.search(numberstring)
>>> print result
<_sre.SRE_Match object at 0x02CEAD40>
>>> result = patternalphaonly.match(numberstring)
>>> print result
<_sre.SRE_Match object at 0x02CEAD40>
谢谢
星形运算符(
*
)表示零次或多次重复。你的字符串没有英文字母的重复,因为它完全是数字,这是完全有效的使用星号(重复零次)。而是使用+
运算符,它表示一个或多个重复。示例:Helpful link on repetition operators.
埃尔达拉提斯说的一切都是真的。但是,对于一个名为:
'patternalphaonly'
的变量,我假设作者希望验证字符串是否只由字母字符组成。如果这是真的,那么我会向正则表达式添加额外的字符串结束锚点,如下所示:或者,更好的是,因为它只在字符串的开头匹配,所以使用首选的
^{pr2}$match
方法:(由于某些尚未解释的原因,它显然更快。)
相关问题 更多 >
编程相关推荐