python `AttributeError: 'NoneType' object has no attribute 'group'`

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

猜你喜欢

转载自blog.csdn.net/weiyang_tang/article/details/82806920
今日推荐