
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
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