正则表达式:AttributeError:'NoneType'对象没有属性'groups'
- 2025-03-21 09:05:00
- admin 原创
- 40
问题描述:
我有一个字符串,我想提取它的子集。这是一个较大的 Python 脚本的一部分。
这是字符串:
import re
htmlString = '</dd><dt> Fine, thank you. </dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'
我想要提取“ Molt bé, gràcies. mohl behh, GRAH-syuhs ”。为此,我使用正则表达式re.search
:
SearchStr = '(</dd><dt>)+ ([w+,.s]+)([&#d;]+)(</dt><dd>)+ ([w,swsw?!.]+) ((<i>)([ws,-]+)(</i>))'
Result = re.search(SearchStr, htmlString)
print Result.groups()
AttributeError: 'NoneType' object has no attribute 'groups'
由于Result.groups()
不起作用,我想要进行的提取也不起作用(即Result.group(5)
和Result.group(7)
)。但我不明白为什么会出现此错误?正则表达式在 TextWrangler 中有效,为什么在 Python 中无效?我是 Python 初学者。
解决方案 1:
您之所以得到它,AttributeError
是因为您正在调用groups
,None
但它没有任何方法。
regex.search
返回None
意味着正则表达式无法从提供的字符串中找到与模式匹配的任何内容。
使用正则表达式时,最好检查是否匹配:
Result = re.search(SearchStr, htmlString)
if Result:
print Result.groups()
解决方案 2:
import re
htmlString = '</dd><dt> Fine, thank you. </dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'
SearchStr = '(</dd><dt>)+ ([w+,.s]+)([&#d;]+)(</dt><dd>)+ ([w,swsw?!.]+) ((<i>)([ws,-]+)(</i>))'
Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)
print Result.groups()
就是这样。表达式包含非拉丁字符,因此通常会失败。您必须解码为 Unicode 并使用 re.U (Unicode) 标志。
我也是初学者,我自己也遇到过几次这个问题。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD