AttributeError: 'NoneType' object has no attribute 'group'
import re
content='*** Hello 2018,I am happy'
regex='\w+.*?\d{4}.*?\w'
result=re.match(regex,content)
print(result.group())
报错:
Traceback (most recent call last):
File "D:/python/Worn/Lib_USE/re_match.py", line 10, in <module>
print(result.group())
AttributeError: 'NoneType' object has no attribute 'group'
错误原因:
re.match()未匹配成功返回None,None是没有group这个属性的
改正错误:
1. 正则表达式写正确
2. 如果返回的是None,就不用group
改正的代码如下
content='*** Hello 2018,I am happy'
regex='.*?\w+.*?\d{4}.*?\w'
result=re.match(regex,content)
if result!=None:
print(result.group())
else:
print('None')
结果:
*** Hello 2018,I
本文详细解析了Python中使用正则表达式进行字符串匹配的常见错误与解决方法,通过具体示例展示了如何修正正则表达式以正确匹配目标内容,并介绍了如何检查匹配结果避免程序异常。
2563

被折叠的 条评论
为什么被折叠?



