这主要是由于没有匹配到元素,之后又调用了group()方法造成的
import re
content = 'hello world'
result = re.match('^w.*d$', content)#这是想只提取world
print(result)
print(result.group())
输出
None
Traceback (most recent call last):
File "D:/000python/0505/5.py", line 6, in <module>
print(result.group())
AttributeError: 'NoneType' object has no attribute 'group'
第一个print函数会打印none,因为match函数只能从头开始匹配,不能从中间开始。而当返回值为none时,再次调用group()方法就会出现AttributeError: 'NoneType' object has no attribute 'group'这类报错。
将上述代码块中的match改成search()就可以避开这类问题了。search函数是先扫描全部的代码块,再进行提取的。
————————————————
修改后:
import re
content = 'hello world'
result = re.search('world', content)#这是想只提取world
print(result)
print(result.group())
输出:
<re.Match object; span=(6, 11), match='world'>
world
修改后:
import re
content = 'worldhello world'
result = re.match('^w.*d$', content)#这是想只提取world
print(result)
print(result.group())
输出
<re.Match object; span=(0, 16), match='worldhello world'>
worldhello world