Python Regular Expression – re.findall()

Spread the love

re.findall() –

The re.findall() method find all occurrences of a pattern in a string and return a list of all matching sub strings.

syntax of re.findall() –

re.findall(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 (optional) – optional setting to modify the behavior of re.findall()

How it works?

Let’s say that we some text.

In [1]: text = """
   ...: I'm fine without you now
   ...: I don't need you here
   ...: I'm fine without you now
   ...: can you disappear?
   ...: I'm fine without you now
   ...: I've given you my heart
   ...: I'm fine without you now
   ...: I've given you, given you everything
   ...: """

And we want to search all occurrences of ‘fine’ word in this text. For that, we have to first import the python re module then use re.findall() method.

In [2]: import re

In [3]: re.findall('fine', text)
Out[3]: ['fine', 'fine', 'fine', 'fine']

As there are 4 occurrences of fine in the text, findall returns the list of all matched strings.

Rating: 1 out of 5.

Leave a Reply