函数match():从字符串的起始部分对模式进行匹配。如果匹配成功,返回一个匹配对象;如果匹配失败,返回None
代码:
import re
result = re.match(r'word', 'hellow word')
print(result)
print(result.group())
输出:
None
Traceback (most recent call last):
File "/home/tarena/search01.py", line 5, in <module>
print(result.group())
AttributeError: 'NoneType' object has no attribute 'group'
分析:
group方法报错,查看变量result值,变量result值为None,因而说明匹配失败,result是个空值,因此group()方法报错
错误原因:
函数match()是从字符串开始位置匹配,开始为hellow,因而匹配失败
正确代码:
import re
result = re.match(r'word', 'word hellow')
print(result)
print(result.group())
正确输出:
<_sre.SRE_Match object; span=(0, 4), match='word'>
word