
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
Python Regular Expression: Search vs Match
The built-in Python module re provides re.search() and re.match(), which are powerful regular expression functions. They are commonly used functions for finding patterns in strings, but they behave differently.
The re.search() Function
The re.search() function checks the entire string for a match. It will return the first match it finds in the string, not just at the beginning. This is helpful when the pattern might appear in the middle or end of the string. If it finds a match, it returns a Match object; if not, it returns None.
Example
In the following example re.search() function looks through the whole string and finds "Python" in the middle and returns a match.
import re text = "Welcome to Python programming" result = re.search("Python", text) if result: print("Match found!") else: print("No match.")
Following is the output of the above code ?
Match found!
The re.match() Function
The re.match() attempts to match a regular expression (regex) pattern only at the beginning of a string. If the specified pattern is found right at the start, it returns a match object. If the pattern appears later in the string or not at all, it returns None.
Example
In the following example re.match() function checks the start of the string. Since "Welcome" is at the beginning, it returns a match. If we try to match "Python", it will return None.
import re text = "Welcome to Python programming" result = re.match("Welcome", text) if result: print("Match found!") else: print("No match.")
Following is the output of the above code ?
Match found!
Key Difference Between search and match Functions
The following are the common differences between re.match() and re.search() functions.
Feature | re.search() | re.match() |
---|---|---|
Checks where? | Anywhere in the string | Only at the beginning of the string |
Returns | Match object if found, else None | Match object if found at start, else None |
Performance | Slightly slower if string is long, as it scans the entire string | Slightly faster if matching at start |
Common Use Cases | Useful for scanning logs, paragraphs, or sentences for keywords | Useful for validation, like form inputs or pattern-based string start check |