Python Regular Expression – re.search()

Spread the love

re.search() –

re.search() searches a pattern anywhere in the string unlike re.match() which only searches at the beginning of a string.

syntax of re.search() –

re.search(pattern, string, flags)

pattern – the regular expression pattern that you want to match

string – the string withing which you want to find the patter

flags – optional setting that modify the behavior of re.search()

Let’s look at an example. Let’s say we are trying to find ‘e’ in ‘aeiou’.

In [2]: re.search('e', 'aeiou')
Out[2]: <re.Match object; span=(1, 2), match='e'>

When a match is find re.search returns a match object. The span tells you the starting and ending index of the match in this case it is 1 and 2 as the match starts at the 1st index and end before the 2nd index. The match tells you the string that is match.

You can get the staring and ending index of the matched object using the start and end method.

In [3]: m = re.search('e', 'aeiou')

In [4]: m.start()
Out[4]: 1

In [5]: m.end()
Out[5]: 2

To get the matched string we use the group method.

In [6]: m.group()
Out[6]: 'e'

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

By default the value of group is 0.

What is the difference between re.search() and re.findall() ?

To find more information about re.findall() – Python regex – re.findall()

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

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

Rating: 1 out of 5.

Leave a Reply