开发者

Python regex gotcha

开发者 https://www.devze.com 2023-04-06 15:16 出处:网络
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)

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

0

精彩评论

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