What is the difference between re.match(), re.search() and re.findall() methods in Python?



Python's re module is useful while working with Regular Expressions, allowing us to search, match and manipulate strings by following specific patterns.

  • re.match(): Checks if a given pattern matches at the beginning of a string. If a match is found, it returns a match object.
  • re.search(): Scans the entire string for the first occurrence of the specified pattern. If it finds a match, it returns a match object.
  • re.findall(): Finds all occurrences of a pattern within the string and returns them as a list.

The re.match() Method

The re.match() method finds a match if it occurs at the start of the string. At the beginning of a string. If not, it gives back None. This method is particularly useful when we want to check that a string begins with a certain substring.

Example

In the following example, we are going to search for the pattern (r'TP') in the given string (Tp Tutorials) using the group() method.

import re
result = re.match(r'TP', 'TP Tutorials Point TP')
print (result.group(0))

Output

Following is the output for the above code.

TP

The re.search() Method

The re.search() method is similar to re.match() but it doesn't limit us to finding matches at the beginning of the string. It scans the entire string to find the first occurrence of a pattern.

Using this method, we can find the substring that can appear anywhere in the string, rather than just at the start.

Example

The following example demonstrates the pattern searching in a string using re.search().

import re
result = re.search(r'Tutorials', 'TP Tutorials Point TP')
print (result.group(0))

Output

Following is the output for the above code.

Tutorials

The re.findall() Method

When using re.findall() method to search for a pattern, it will return all occurrences of that pattern into a list. It searches from the beginning or end of the specified string and works like both re.search() and re.match().

Example

Here, we are going to use the re.findall() method to search the given pattern of the string.

import re
result = re.search(r'TP', 'TP Tutorials Point TP')
print (result.group())

Output

Following is the output for the above code.

TP
Updated on: 2025-02-27T17:24:17+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements