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

浅浅的花香味﹌ 2022-05-11 09:28 404阅读 0赞

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

  1. import re
  2. content='*** Hello 2018,I am happy'
  3. regex='\w+.*?\d{4}.*?\w'
  4. result=re.match(regex,content)
  5. print(result.group())

报错:

  1. Traceback (most recent call last):
  2. File "D:/python/Worn/Lib_USE/re_match.py", line 10, in <module>
  3. print(result.group())
  4. AttributeError: 'NoneType' object has no attribute 'group'

错误原因:

  1. re.match()未匹配成功返回None,None是没有group这个属性的
  2. 改正错误:
  3. 1. 正则表达式写正确
  4. 2. 如果返回的是None,就不用group

改正的代码如下

  1. content='*** Hello 2018,I am happy'
  2. regex='.*?\w+.*?\d{4}.*?\w'
  3. result=re.match(regex,content)
  4. if result!=None:
  5. print(result.group())
  6. else:
  7. print('None')

结果:

  1. *** Hello 2018,I

发表评论

表情:
评论列表 (有 0 条评论,404人围观)

还没有评论,来说两句吧...

相关阅读