Search⌘ K
AI Features

Python regex `match` vs. `search` functions

Discover how to differentiate between Python's regex match and search functions. This lesson helps you understand their distinct behaviors in locating patterns at the start versus anywhere in a string, enabling you to apply the right function for effective string searching in your Python projects.

Python Matching Versus Searching

We have learned so far that Python offers two different primitive operations:

  • match
  • search

So, how they are different to each other?

Note that match checks for a match only at the beginning of a string, while search checks for a match anywhere in the string!

Example 1

Let’s try to find the word Python:

Python
#!/usr/bin/python
import re
line = "Learn to Analyze Data with Scientific Python";
m = re.search( r'(python)', line, re.M|re.I)
if m:
print "m.group() : ", m.group()
else:
print "No match by obj.search!!"
m = re.match( r'(python)', line, re.M|re.I )
if m:
print "m.group() : ", m.group()
else:
print "No match by obj.match"

You will be able to see that, match function won’t find the word “Python”, but search can! Also note the use of the re.I (case insensitive) option.

Example 2:

Python
#!/usr/bin/python
import re
email = "hello@leremove_thisarntoanalayzedata.com ";
# m = re.match ("remove_this", email) // This will not work!
m = re.search("remove_this", email)
if m:
print "email address : ", email[:m.start()] + email[m.end():]
else:
print "No match!!"