Python正则表达式;为什么search&match似乎在数字字符串中查找alpha字符?

2024-09-30 22:14:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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>

谢谢


Tags: reobject环境windowsmatchresultatprint
2条回答

星形运算符(*)表示零次或多次重复。你的字符串没有英文字母的重复,因为它完全是数字,这是完全有效的使用星号(重复零次)。而是使用+运算符,它表示一个或多个重复。示例:

>>> n = "3534543234543"
>>> r1 = re.compile("[a-zA-Z]*")
>>> r1.match(n)
<_sre.SRE_Match object at 0x07D85720>
>>> r2 = re.compile("[a-zA-Z]+") #using the + operator to make sure we have at least one letter
>>> r2.match(n)

Helpful link on repetition operators.

埃尔达拉提斯说的一切都是真的。但是,对于一个名为:'patternalphaonly'的变量,我假设作者希望验证字符串是否只由字母字符组成。如果这是真的,那么我会向正则表达式添加额外的字符串结束锚点,如下所示:

patternalphaonly = re.compile('^[a-zA-Z]+$')
result = patternalphaonly.search(numberstring)

或者,更好的是,因为它只在字符串的开头匹配,所以使用首选的match方法:

^{pr2}$

(由于某些尚未解释的原因,它显然更快。)

相关问题 更多 >