re.search没有返回字符串,但re.findall确实如此

时间:2013-11-11 23:38:34

标签: python regex search findall

我在这里有点困惑,为什么会发生这种情况。这是简短的代码:

with open("file.xml") as xmlFile: # reading the xmlFile
    xmlLines=list()
    for line in xmlFile:
        newLine=xmlSearch.findall(line)
        print newLine

退回:(出于安全原因,我更改了实际输出)

[]
[]
[]
[]
[]
['TEXT_IN_STRING_FORMAT-SENSITIVE_DATA']
['TEXT_IN_STRING_FORMAT-SENSITIVE_DATA']
['TEXT_IN_STRING_FORMAT-SENSITIVE_DATA']
['TEXT_IN_STRING_FORMAT-SENSITIVE_DATA']
['TEXT_IN_STRING_FORMAT-SENSITIVE_DATA']
['TEXT_IN_STRING_FORMAT-SENSITIVE_DATA']
[]
[]
[]
[]
[]

但是,如果我使用re.search,我会得到以下内容:

with open("file.xml") as xmlFile: # reading the xmlFile
    xmlLines=list()
    for line in xmlFile:
        newLine=re.search(r"\w/([\w\-]+)",line)
        print newLine

(出于安全考虑,编辑输出以防万一)

None
None
None
None
None
<_sre.SRE_Match object at 0x000....SNIP>
<_sre.SRE_Match object at 0x000....SNIP>
<_sre.SRE_Match object at 0x000....SNIP>
<_sre.SRE_Match object at 0x000....SNIP>
<_sre.SRE_Match object at 0x000....SNIP>
<_sre.SRE_Match object at 0x000....SNIP>
None
None
None
None
None

知道为什么这是开心的吗?从我在Python的文档和本网站上找到的例子中,re.search也应该返回一个字符串。最后添加.groups()会导致以下错误:

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

我正在使用Python 2.7

1 个答案:

答案 0 :(得分:3)

re.search会返回MatchObjectNone - 请参阅the re.search docs

re.findall会返回字符串或元组列表 - 请参阅the re.findall docs

相关问题