Last Updated : 12 Jul, 2025
Python’s re module provides powerful tools to search, match and manipulate text using regular expressions. Two commonly used functions are re.search(), which finds the first occurrence of a pattern in a string and re.findall(), which retrieves all matches of a pattern throughout the string. Understanding how each works will help you effectively handle text processing tasks.
What is re.search() ?re.search() function scans through a string, looking for the first location where the regular expression pattern produces a match. It returns a match object if a match is found, otherwise returns None.
Example:
Python
import re
s = "My favorite fruits are apple, banana, and mango."
res = re.search(r'\b\w*a\b', s)
if res:
print(res.group())
else:
print("Not found.")
Explanation:
re.findall() function returns all non-overlapping matches of a pattern in a string as a list of strings. If the pattern has capturing groups, it returns a list of tuples.
Python
import re
s = "My favorite fruits are apple, banana, and mango."
res = re.findall(r'\b\w*a\b', s)
print(res)
Explanation:
Capturing groups in regular expressions are used to extract specific parts of the matched text. You create a group by placing part of the pattern inside parentheses ().
Example 1: In this example, we want to extract the price (just the number) after the word Price by using re.search().
Python
import re
s = "Price: $30, Discount: $5"
res = re.search(r'Price: \$(\d+)', s)
if res:
print(res.group(1))
Explanation:
Example 2: Now, suppose you want to extract all numbers that come after a dollar sign ($) in the sentence. You can use re.findall() for this.
Python
import re
s = "Price: $30, Discount: $5"
res = re.findall(r'\$(\d+)', s)
print(res)
Explanation:
Both functions are used to find patterns in text, but they serve different purposes depending on whether you need a single match or all matches. The table below highlights the key differences to help you choose the right function for your task.
Feature
re.search()
re.findall()
Return Type
Returns a Match object or None
Returns a list of matching strings or tuples
Match Count
Returns only the first match
Returns all non-overlapping matches
Use Case
Best for checking if a pattern exists
Best for extracting multiple matches
Access Groups
Allows access to individual groups using .group()
Capturing groups are returned as tuples
Performance
Stops at first match (faster in some cases)
Scans the entire string
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4