我在Idle中运行搜索,在Windows总线上的Python 2.7中运行.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>
Run Code Online (Sandbox Code Playgroud)
谢谢
星号运算符(*)表示零次或多次重复.你的字符串没有重复的英文字母,因为它完全是数字,这在使用星形时是完全有效的(重复零次).而是使用+表示一次或多次重复的运算符.例:
>>> 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)
Run Code Online (Sandbox Code Playgroud)