Python Regular Expression – re.match()

Spread the love

re.match() –

re.match() method matches a pattern at the beginning of a string and return a match object. It only searches at the beginning of a string.

syntax of re.match() –

re.match(pattern, string, flags)

pattern – the regular expression pattern that you want to match

string – the string in which you want to search the pattern.

flags – a modifier that helps you customize the behavior of the function

Let’s look at an example.

In [1]: import re

In [2]: re.match('e', 'aeiou')

Although the letter ‘e’ is in the string ‘aeiou’ but python regex return None as ‘e’ is not at the beginning of a string.

But if I search for ‘a’ we will get a match object.

In [3]: re.match('a', 'aeiou')
Out[3]: <re.Match object; span=(0, 1), match='a'>

The span tells you the starting and ending index of the matched string and match tells you the string that is matched.

You can also get the starting and ending index using start and end method.

In [4]: m = re.match('a', 'aeiou')

In [5]: m.start()
Out[5]: 0

In [6]: m.end()
Out[6]: 1

To get the matched string we use the group method.

In [7]: m.group()
Out[7]: 'a'

In [8]: m.group(0)
Out[8]: 'a'

By default the value of group is 0.

What the difference between re.match() vs re.findall() ?

You can find more information about re.findall() here – python regex – re.findall()

  1. re.match() returns a match object while re.findall() returns a list of all matched string.
  2. re.match() only returns the first match in the string while re.findall() returns all the matches in the string.
In [9]: re.match('Python', 'Python is awesome. I love Python')
Out[9]: <re.Match object; span=(0, 6), match='Python'>

In [10]: re.findall('Python', 'Python is awesome. I love Python')
Out[10]: ['Python', 'Python']

Rating: 1 out of 5.

Leave a Reply