I know this topic has already been discussed multiple times here on StackOverflow, but I'm looking for a better answer.
While I appreciate the differences, I was not really able to find a definitive explanation of why the re
module in python provides both match()
and search()
.
Couldn't I get the same behavior with search()
, if I prepend ^
in single line mode, and /A
in multiline mode? Am I missing anything?
I tried to understand the implementation looking at the _sre.c code and I understand that the search (sre_search()
) is actually implemented moving the pointer in the string to be searched, and applying the sre_match()
on it, until a match is found.
So I guess that using the re.match()
might be slightly faster than the corresponding regular expression (with ^
or /A
) using the re.search()
. Is that the reason?
I also researched the python-dev ML archives but to no avail.
>>> string="""first line
... second line"""
>>> print re.match('first', string, re.MULTILINE)
<_sre.SRE_Match object at 0x1072ae7e8>
>>> print re.match('second', string, re.MULTILINE)
None
>>> print re.search('\Afirst', string, re.MULTILINE)
<_sre.SRE_Match object at 0x1072ae7e8>
>>> print re.search('\Asecond', string, re.MULTILINE)
None