What is the difference between the search()
and match()
functions in the Python re
module?
I've read the Python 2 documentation (Python 3 documentation), but I never seem to remember it.
matchpythonregexsearchstring-matching
What is the difference between the search()
and match()
functions in the Python re
module?
I've read the Python 2 documentation (Python 3 documentation), but I never seem to remember it.
Best Answer
re.match
is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using^
in the pattern.As the re.match documentation says:
re.search
searches the entire string, as the documentation says:So if you need to match at the beginning of the string, or to match the entire string use
match
. It is faster. Otherwise usesearch
.The documentation has a specific section for
match
vs.search
that also covers multiline strings:Now, enough talk. Time to see some example code: