re.search not returning strings, but re.findall does

走远了吗. 提交于 2019-12-13 06:26:41

问题


I'm getting a bit confused here as to why this is happening. Here's the short and simple code:

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

RETURNS: (I changed the actual output for security reasons)

[]
[]
[]
[]
[]
['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']
[]
[]
[]
[]
[]

However, if I use re.search I get the following:

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

(edited output just in case, for security reasons)

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

Any idea why this is happpening? From the examples I found on Python's docs and on this website, re.search should be returning a string as well. Addding the .groups() at the end results in the following error:

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

I'm using Python 2.7


回答1:


re.search returns a MatchObject or None - See the re.search docs.

re.findall returns a list of strings or tuples - see the re.findall docs.



来源:https://stackoverflow.com/questions/19918169/re-search-not-returning-strings-but-re-findall-does

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!