环境:ubuntu
语言:python
问题:正则表达式出现AttributeError: 'NoneType' object has no attribute 'group'提示
原因:re.match()由于没有匹配到元素,之后又调用了group()方法造成的
分析:很可能是由于正则表达式出错造成的,尤其是使用标签时容易出错
解决:在使用正则表达式时使用try捕获错误,一旦发现错误,立马反馈,同时使用if增强检测,当然也可以不使用try捕获,直接使用if判断,请参考下方代码
代码:
下面的正则表达式故意写错,正确的写法:r"^<(?P<p1>\w*)><(?P<p2>\w*)>.*</(?P=p2)></(?P=p1)>$"
import re
file_content = "<body><h1>hahahaha</h1></body>"
judge_rule = r"^<(?P<p1>\w*)><(?P<p2>\w*)>.*</(?P=p1)></(?P=p1)>$" # 特别注意这一条正则表达式
try:
temp = re.match(judge_rule, file_content)
if temp is None: # 进一步确定错误类型
print("match()的返回值为空")
print(temp.group())
except AttributeError:
print("请检查正则表达式标签是否对应")
except Exception as result:
print("出错原因:", result)