Python + Regex:AttributeError:'NoneType'对象没有属性'groups'

jO.*_*jO. 22 python regex

我有一个字符串,我想提取一个子集.这是更大的Python脚本的一部分.

这是字符串:

import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'
Run Code Online (Sandbox Code Playgroud)

我要拉出" Moltbé,gràcies.mohlbehh,GRAH-syuhs ".为此,我使用正则表达式re.search:

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'

Result = re.search(SearchStr, htmlString)

print Result.groups()
AttributeError: 'NoneType' object has no attribute 'groups'
Run Code Online (Sandbox Code Playgroud)

既然Result.groups()不起作用,我想做的提取也没有(即Result.group(5)Result.group(7)).但我不明白为什么我会收到这个错误?正则表达式在TextWrangler中有效,为什么不在Python中呢?我是Python的初学者.

thk*_*ang 46

你得到AttributeError,因为你调用groupsNone,还没有任何方法.

regex.search返回None意味着正则表达式找不到与提供的字符串中的模式匹配的任何内容.

使用正则表达式时,最好检查一下是否匹配:

Result = re.search(SearchStr, htmlString)

if Result:
    print Result.groups()
Run Code Online (Sandbox Code Playgroud)


ant*_*avy 10

import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'

Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)

print Result.groups()
Run Code Online (Sandbox Code Playgroud)

这样工作.表达式包含非拉丁字符,因此通常会失败.您必须解码为Unicode并使用re.U(Unicode)标志.

我也是初学者,我自己也曾多次面对这个问题.