开发者

Python regular expression; why do the search & match appear to find alpha chars in a number string?

I'm running search below Idle, in Python 2.7 in a Windows Bus. 64 bit environment.

According to RegexBuddy, the search pattern ('patternalphaonly') should not produce a match against a string of digits.

I looked at "http://docs.python.org/howto/regex.html", but did not see anything there that would explain why the search and match appear to be successful in finding something matching the pattern.

Does anyone know what I'm doing wrong, or misunderstanding?

>>> 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.开发者_Python百科SRE_Match object at 0x02CEAD40>

Thanks


The star operator (*) indicates zero or more repetitions. Your string has zero repetitions of an English alphabet letter because it is entirely numbers, which is perfectly valid when using the star (repeat zero times). Instead use the + operator, which signifies one or more repetitions. Example:

>>> 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.


Everything eldarerathis says is true. However, with a variable named: 'patternalphaonly' I would assume that the author wants to verify that a string is composed of alpha chars only. If this is true then I would add additional end-of-string anchors to the regex like so:

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

Or, better yet, since this will only ever match at the beginning of the string, use the preferred match method:

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

(Which, as John Machin has pointed out, is evidently faster for some as-yet unexplained reason.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜