
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I find all matches to a regular expression in Python?
To find all matches to a regular expression in Python, you can use the re module, which provides regular expression matching operations. Here are a few methods to find all matches to regular expressions.
- Using re.findall(pattern, string)
- Using re.finditer(pattern, string)
- re.compile combined with findall or finditer
Using re.findall(pattern, string)
The re.findall() method finds all non-overlapping matches of the pattern in the string and returns them as a list of strings.
This method returns a list of strings. If the pattern contains capturing groups, it returns a list of tuples, with each tuple containing the matches for the capturing groups.
Example
In the following example, the pattern r"at" searches for all occurrences of "at" in the text. The re.findall method returns all three matches as a list.
import re text = "The cat and the hat are in the mat." pattern = r"at" # raw string to prevent issues with backslashes result = re.findall(pattern, text) print(result)
Following is the output for the above code-
['at', 'at', 'at']
Using re.finditer(pattern, string)
The re.finditer() method returns an iterator of MatchObject objects yielding match objects for all non-overlapping matches of the pattern in the string.
Example
Here, the re.finditer() method returns an iterator. Each element from the iterator is a MatchObject, which contains more information about the match, such as the starting and ending positions.
import re text = "The cat and the hat are in the mat." pattern = r"at" result = re.finditer(pattern, text) for match in result: print(match)
Following is the output for the above code-
<re.Match object; span=(5, 7), match='at'> <re.Match object; span=(17, 19), match='at'> <re.Match object; span=(30, 32), match='at'>
Using 're.compile()' combined with findall or finditer
In this technique, the re.compile() function compiles a regular expression pattern into a regular expression object, which can then be used to find matches using findall or finditer.
Example
This example combines re.compile with finditer. The pattern is first compiled, and then finditer is used to return an iterator of match objects.
import re text = "The cat and the hat are in the mat." pattern = re.compile(r"(c|h|m)at") # Compile the pattern result = pattern.finditer(text) for match in result: print(match.group(0)) print(match.group(1))
Following is the output for the above code-
cat c hat h mat m