Python re.findall() – Find in String using Regular Expression

Python re.findall() Function

re.findall() function returns all non-overlapping matches of a pattern in a string. The function returns all the findings as a list. The search happens from left to right.

In this tutorial, we will learn how to use re.findall() function with the help of example programs.

Syntax – re.findall()

The syntax of re.findall() function is

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

where

ParameterDescription
pattern[Mandatory] The pattern which has to be found in the string.
string[Mandatory] The string in which the pattern has to be found.
flags[Optional] Optional flags like re.IGNORECASE, etc.

Return Value

The function returns a List object.

Example 1: re.findall() – Substring in String

In this example, we will take a substring and a string. We will find all the non-overlapping matches of given substring in the string using re.findall() function. We shall print the list returned by findall() function.

Python Program

import re

pattern = 'abc'
string = 'abcdefabcab'
result = re.findall(pattern, string)
print(result)
Run Code Copy

Output

['abc', 'abc']

Example 2: re.findall() – Pattern in String

In this example, we will take a pattern and a string. The pattern is a continuous occurrence of alphabets. We will find all the non-overlapping matches of this pattern in the string using re.findall() function. We shall print the list returned by findall() function.

Python Program

import re

pattern = '[a-z]+'
string = 'abc---cab-efg_web'
result = re.findall(pattern, string)
print(result)
Run Code Copy

Output

['abc', 'cab', 'efg', 'web']

Example 3: re.findall() – Non-overlapping Occurrences

In this example, we will take a pattern and a string, such that the string contains overlapping occurrences of the pattern. findall() function should return only non-overlapping occurrences.

Python Program

import re

pattern = 'aba'
string = 'ababaiiaba'
result = re.findall(pattern, string)
print(result)
Run Code Copy

Output

['aba', 'aba']

Example 4: re.findall() – flags

In this example, we will take a pattern and a string. We will find the matches for pattern in the given string with an optional flag.

Python Program

import re

pattern = '[a-z]+'
string = 'aBC---CAB-eFg_web'
flags = re.IGNORECASE
result = re.findall(pattern, string, flags)
print(result)
Run Code Copy

Output

['aBC', 'CAB', 'eFg', 'web']

You may try the above Python program without flags parameter. You would get a different output, because in the above code, we are telling findall() function to ignore case while finding matches for the pattern in string with the help of flags parameter.

Summary

In this tutorial of Python Examples, we learned how to use re.findall() function to get all the matchings for a given pattern in a string, with the help of example programs.

Code copied to clipboard successfully 👍