Python regex gotcha
Could you explain me why th开发者_StackOverflow中文版e first regex doesn't match?
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> import re
>>> re.match(r'\d','.0')
>>> re.match(r'.\d','.0')
<_sre.SRE_Match object at 0x109adbd30>
re.match()
tries to match from the beginning of the string.
Use re.search()
instead if you want to locate a match anywhere in the string.
PS: You might want to escape the .
, because it's a metacharacter that matches any1 character (so x0
would match your second example).
>>> re.match(r'\.\d', 'x0')
>>> re.match(r'.\d', 'x0')
<_sre.SRE_Match object at 0x01F67138>
1 except newlines, unless re.DOTALL
is used.
Because you're using match
and that matches a string from beginning (like if you used ^
)
Try re.search
For reference to search vs match: http://docs.python.org/library/re.html#search-vs-match
精彩评论