你能解释一下为什么第一个正则表达式不匹配吗?
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>
答案 0 :(得分:7)
re.match()
尝试从字符串的开头进行匹配。
如果要在字符串中的任何位置找到匹配项,请使用re.search()
。
PS:您可能想要转义.
,因为它是一个与任何 1 字符匹配的元字符(因此x0
将匹配您的第二个示例)。
>>> re.match(r'\.\d', 'x0')
>>> re.match(r'.\d', 'x0')
<_sre.SRE_Match object at 0x01F67138>
除了换行符之外 1 ,除非使用re.DOTALL
。
答案 1 :(得分:3)
因为您正在使用match
并且从头开始匹配字符串(就像您使用^
一样)
尝试re.search
答案 2 :(得分:1)