![]() |
VOOZH | about |
re.findall() method in Python helps us find all pattern occurrences in a string. It's like searching through a sentence to find every word that matches a specific rule. We can do this using regular expressions (regex) to create the pattern and then use re.findall() to get a list of matches.
Let's say we want to find all words that start with "P" in a string.
['Python', 'Powerful']
Table of Content
The syntax of re.findall() is simple:
import re
result = re.findall(pattern, string)
The return type of re.findall() is always a list. This list contains all the non-overlapping matches of the pattern in the string. If no match is found, it will return an empty list.
By default, re.findall() is case-sensitive. To make it case-insensitive, we can pass the re.IGNORECASE flag.
['Python', 'python']
Here we use a pattern that matches any number. The regular expression \d+ looks for one or more digits in a row. So if the text contains numbers like "12 apples and 5 bananas", it will find "12" and "5" and give us those as the result
['12', '5', '300']
Here we use a pattern to find dates written in the format YYYY-MM-DD. The regular expression \d{4}-\d{2}-\d{2} is designed to find a four-digit year, followed by a two-digit month and a two-digit day. If the text contains "2024-12-25" and "2025-01-15" it will pick them out as matches.
['2024-12-25', '2025-01-15']