Back

Explore Courses Blog Tutorials Interview Questions
0 votes
5 views
in Python by (47.6k points)

What is the difference between the search() and match() functions in the Python re module?

I've read the documentation (current documentation), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.

1 Answer

0 votes
by (106k points)

The re.match is attached at the beginning of the string. Which has nothing to do with newlines, so it is not the same as using ^ in the pattern.

What does re.match documentation says:

If in the regular expression pattern zero or more characters at the beginning of string match then return a corresponding MatchObject instance. Otherwise, return None if the string does not match the pattern.

To locate a match anywhere in the string, you can use search().

What re.search documentation says:

The re.search() scans through string looking for a location where the regular expression pattern produces a match, and then it returns a corresponding MatchObject instance. Otherwise, it returns None if no position in the string matches the pattern.

So, to match at the beginning of the string, or to match the entire string you can use match which is faster. Otherwise, you can use search.

Now we will see the difference between match() and search():-

Based on regular expressions Python offers two different primitive operations  Which are match which checks for a match only at the beginning of the string, and the other one is  search which checks for a match anywhere in the string.

Now we will look and code example of match() and search():-

import re

a = "123abc"

t = re.match("[a-z]+",a)

x = re.search("[a-z]+",a)

print(t)

print(x)

image

Browse Categories

...