Python Regular Expression –

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

syntax of –, 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

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

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

When a match is find 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 ='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]:
Out[6]: 'e'

In [7]:
Out[7]: 'e'

By default the value of group is 0.

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

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

  1. returns a match object and re.findall() returns a list of all matched string.
  2. returns only the first matched string while re.findall() return all the matches in the string.
In [8]:'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