re.search() vs re.match() – Python
Last Updated :
08 May, 2025
When working with regular expressions (regex) in Python, re.search() and re.match() are two commonly used methods for pattern matching. Both are part of the re module but function differently. The key difference is that re.match() checks for a match only at the beginning of the string, while re.search() searches the entire string for the pattern. Example:
Python
import re
s = '''We are learning regex with geeksforgeeks
regex is very useful for string matching.'''
a = re.match(r"regex", s)
print(a)
b = re.search(r"regex", s)
print(b)
OutputNone
<re.Match object; span=(16, 21), match='regex'>
Explanation:
- re.match() searches for “regex” only at the beginning of the string. Since it’s not at the start, it returns None.
- re.search() searches for “regex” anywhere in the string. It finds it at index 16 and returns a match object.
When to use what?
Both re.match() and re.search() are powerful tools for pattern matching in strings. However, knowing when to use each can significantly improve both efficiency and accuracy in your code. Let’s dive into understanding when to use re.match() and re.search().
1. Use re.match(): When you’re only interested in checking if a string begins with a specific pattern, you can use re.match(). This is especially useful for validating scenarios like file formats, prefixes or any fixed starting patterns in strings. For example, checking if a string starts with a particular number, letter, or keyword.
Example 1: Checking if a string starts with a number
Python
import re
res = re.match(r"\d{4}", "2025 is the year") # Matches "2025"
print(res)
Output<re.Match object; span=(0, 4), match='2025'>
Explanation: re.match(r”\d{4}”, “2025 is the year”) checks for four digits at the start of the string and since “2025” appears right at the beginning, it returns a match object.
Example 2: Matching a string that starts with a capital letter
Python
import re
res= re.match(r"^[A-Z]", "Hello world") # Matches
print(res)
Output<re.Match object; span=(0, 1), match='H'>
Explanation: re.match(r”^[A-Z]”, “Hello world”) checks if the string starts with an uppercase letter from A to Z and since “H” is uppercase at the beginning, it returns a match object.
2. Use re.search(): when the pattern can appear anywhere in the string. It’s ideal for searching, filtering or scanning large texts like logs, documents or datasets.
Example 1: Searching for a keyword anywhere in the text
Python
import re
res = re.search(r"error", "Server error at 5:00 PM") # Matches "error"
print(res)
Output<re.Match object; span=(7, 12), match='error'>
Explanation: re.search(r”error”, “Server error at 5:00 PM”) looks for the substring “error” anywhere in the text and since it appears after “Server”, it finds a match and returns a match object.
Example 2: Finding the first occurrence of ‘apple’ anywhere in the string.
Python
import re
res = re.search(r"apple", "I have an apple and an orange.")
print(res)
Output<re.Match object; span=(10, 15), match='apple'>
Explanation: re.search(r”apple”, “I have an apple and an orange.”) searches for the first occurrence of the substring “apple” in the string. Since “apple” appears in the text, it finds a match and returns a match object.
Difference between re.search() vs re.match()
In Python regex, re.match() and re.search() both find patterns, but differ in where they look. The table below highlights their key differences to help you choose the right one.
Feature
| re.match()
| re.search()
|
---|
Search Location
| Only at the beginning of the string.
| Anywhere in the string.
|
---|
Return Value
| Match object if at the start; otherwise None.
| Match object for first match; otherwise None.
|
---|
Use Case
| Match pattern at the start.
| Find pattern anywhere in the string.
|
---|
Example
| re.match(r”hello”, “hello world”) (matches)
| re.search(r”world”, “hello world”) (matches)
|
---|
Behavior
| if No Match Returns None if no match at the start.
| Returns None if no match anywhere.
|
---|
Performance
| Faster for start-of-string matching.
| More flexible but may be slower.
|
---|
Similar Reads
Python | re.search() vs re.match()
When working with regular expressions (regex) in Python, re.search() and re.match() are two commonly used methods for pattern matching. Both are part of the re module but function differently. The key difference is that re.match() checks for a match only at the beginning of the string, while re.sear
4 min read
Python Regex: re.search() VS re.findall()
Prerequisite: Regular Expression with Examples | Python A Regular expression (sometimes called a Rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations. Regular expres
3 min read
re.search() in Python
re.search() method in Python helps to find patterns in strings. It scans through the entire string and returns the first match it finds. This method is part of Python's re-module, which allows us to work with regular expressions (regex) simply. Example: [GFGTABS] Python import re s = "Hello, we
3 min read
re.match() in Python
re.match method in Python is used to check if a given pattern matches the beginning of a string. Itâs like searching for a word or pattern at the start of a sentence. For example, we can use re.match to check if a string starts with a certain word, number, or symbol. We can do pattern matching using
2 min read
re.sub() - Python RegEx
re.sub() method in Python parts of a string that match a given regular expression pattern with a new substring. This method provides a powerful way to modify strings by replacing specific patterns, which is useful in many real-life tasks like text processing or data cleaning. [GFGTABS] Python import
2 min read
Regex Cheat Sheet - Python
Regex or Regular Expressions are an important part of Python Programming or any other Programming Language. It is used for searching and even replacing the specified text pattern. In the regular expression, a set of characters together form the search pattern. It is also known as the reg-ex pattern.
9 min read
re.MatchObject.span() Method in Python - regex
re.MatchObject.span() method returns a tuple containing starting and ending index of the matched string. If group did not contribute to the match it returns(-1,-1). Syntax: re.MatchObject.span() Parameters: group (optional) By default this is 0. Return: A tuple containing starting and ending index o
2 min read
Verbose in Python Regex
In this article, we will learn about VERBOSE flag of the re package and how to use it. re.VERBOSE : This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pat
3 min read
Python String rindex() Method
Python String rindex() method returns the highest index of the substring inside the string if the substring is found. Otherwise, it raises ValueError. Let's understand with the help of an example: [GFGTABS] Python s = 'geeks for geeks' res= s.rindex('geeks') print(res) [/GFGTABS]Outp
2 min read
Python String rfind() Method
Python String rfind() method returns the rightmost index of the substring if found in the given string. If not found then it returns -1. Example[GFGTABS] Python s = "GeeksForGeeks" print(s.rfind("Geeks")) [/GFGTABS]Output8 Explanation string "GeeksForGeeks" contains the substring
4 min read