当前位置:首页 > 日记本 > 正文内容

python正则获取不到值报错解决方案:AttributeError: 'NoneType' object has no attribute 'group'

zhangchap2年前 (2022-04-20)日记本321

以前的代码:

url_www = re.search('https://(\w+).wanchemi.com/(\d+).html', w_url, flags=re.I).group(2)

若正则匹配不到值的时候则会报:AttributeError: 'NoneType' object has no attribute 'group'


正确的写法:

python版本>=3.8之后:


if (url_www := re.search('https://(\w+).wanchemi.com/(\d+).html', w_url, flags=re.I)) is not None:
    url_www = url_www.group(2)


python版本 < 3.8:


url_www = re.search('https://(\w+).wanchemi.com/(\d+).html', w_url, flags=re.I)
if url_www :
    url_www = url_www.group(2)

3.8 之后更精简


参考:https://stackoverflow.com/questions/15080078/nonetype-object-has-no-attribute-group

标签: 正则表达式
分享给朋友:

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。