Python re.findall() method



The Python re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings. If the pattern includes capturing groups then re.findall() returns a list of tuples containing the matched groups.

The re.findall() method takes three arguments such as the pattern, the string to search and flags to modify the search behavior.

The methods re.search() or re.match() which return only the first match whereas method re.findall() finds all matches by making it useful for extracting multiple instances of a pattern from a text.

Syntax

Below are the syntax and parameters of Python re.findall() method −

re.findall(pattern, string, flags=0)

Parameters

Following are the parameters of the python re.findall() method −

  • pattern: The regular expression pattern to search for.
  • string: The string to search within.
  • flags(optional): These flags modify the matching behavior

Return value

This method returns a list of all non-overlapping matches of the pattern in the string.

Example 1

Following is the basic example of using the re.findall() method. In this example the pattern '\d+' is used to find all numeric sequences in the string and the method re.findall() returns a list of all matches −

import re

result = re.findall(r'\d+', 'There are 123 apples and 456 oranges.')
print(result) 

Output

['123', '456']

Example 2

In this example the pattern '\b\w+\b' is used to find all words in the string. It returns a list of words −

import re

result = re.findall(r'\b\w+\b', 'Hello, world! Welcome to Python.')
print(result)  

Output

['Hello', 'world', 'Welcome', 'to', 'Python']

Example 3

Here in this example re.MULTILINE flag allows '^' to match the start of each line in a multiline string. The re.findall() method returns all matches from each line −

import re

text = """Hello
hello
HELLO"""
result = re.findall(r'^hello', text, re.IGNORECASE | re.MULTILINE)
print(result)  

Output

['Hello', 'hello', 'HELLO']
python_modules.htm
Advertisements