问题
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