Python re.findall() Method Tutorial

Regular Expression or re is a method used to match characters by using patterns. Python provides the regular expression functions via the re module. The re module is a built-in module and there is no need to install it. The findall() method is provided by the re module and used to math all regular expressions for a given string or text.

re.findall() Method Syntax

The re.findall() method has the following syntax where both of the REGEX and STRING parameters are required.

re.findall(REGEX , STRING)
  • REGEX is the regex pattern which will be applied to the STRING and the result matches will be returned. This parameter is required.
  • STRING is the string or text which will be searched for the specified REGEX pattern. This parameter is required.

Regex Characters and Patterns

Before starting examples with the re.findall() regex matching examples lets list some popular and useful regex characters and patterns with the findall() method.

[]Represent special character class
^The begging of the line
$The end of the line
.Any single character
?Zero or more occurrence for the specified character
*Any number of occurrences
+One or more occurences
{}Group a regex
()Enclose a group of regex

re.findall() Examples

In the following example we will use to find and match alphabet and numbers with the specified regex. Then provide it to the re.findall() method which will return all matched lines as a list.

import re

re_alphabet= "python.*"

re_number= "\d+"

text = """ I like the web site
           This site is the best site of the 2020"""

match = re.findall(re_alphabet , text)

match = re.findall(re_number , text)

The output will be like below. As we can see as the findall() method may return zero, single or more matches the resulted matches will be provided as lists. Below we can see that every math is provided as a list item.



Leave a Comment