re.search vs re.match in Python

In this tutorial, we will learn about the differences between two popular methods used in regular expression re.search vs re.match in Python. We will first look at what regular expressions are, how to use them in Python. Then we will move onto these two methods. So let’s get to it.

Regular Expressions

A sequence of characters that are found in search patterns is called Regular Expressions. They are generally used to match strings or for input validation. They are applied in Formal Languages or Automata.

RegEx in Python

Regular Expression also called RegEx, in short, has a separate module in Python. The built-in package re provides us with all the functions for regular expressions. We do have to install any package separately.

import re

Search Function in re

The search function looks for the given pattern in a string. If it finds the pattern then it returns a Match object. To know more about Match objects go to https://docs.python.org/2.0/lib/match-objects.html.

If not then it returns None. In case of multiple patterns found it returns only the first occurrence.

Let us take an example to understand this function. Suppose a string with this sentence.

string = "The quick brown fox jumps over the lazy dog"

Now in this string, we want to find the alphabet ‘j’.

So we write :

x = re.search('j',string)
print(x.start())

We get the output as 20

Match Function in re

The match functions search for the same expression at the beginning of the given text. If it matches then just like search function this also returns a Match object. Else it returns None.

Let’s again take up an example with code. We use the same string as above.

x = re.match("er",string)
print(x)

We get the output as None.

re.search vs re.match in Python

Let us now take the same string and search for the same pattern using the two functions and minutely observe the differences.

txt = "friends"
x = re.match("d",txt)
y = re.search("d",txt)

Now let’s see the results

print("Match result : " + str(x))
>>> Match result : None
print("Search result : " + str(y))
>>> Search result : <re.Match object; span=(5, 6), match='d'>

 

So match function only checks the beginning of the texts for the pattern while the search function scans the entire text for the pattern.

Hope you find this tutorial useful. 🙂

To know more about regular expression in Python go to https://docs.python.org/3.4/library/re.html

 

Leave a Reply

Your email address will not be published. Required fields are marked *