Nearby lessons
128 of 159Python - Regex match, fullmatch and search
- Understand how match() checks a pattern at the beginning of the target string
- Understand how fullmatch() requires the complete target string to match the pattern
- Understand how search() finds the first occurrence of a pattern anywhere in the target string
- Compare the behaviour of match(), fullmatch() and search() using the same target and pattern
- Choose the right re function for a requirement - beginning check, complete validation, or first occurrence search
Introduction
Python's re module provides several important functions for working with Regular Expressions.
The module provides functions such as:
match() fullmatch() search() findall() finditer() sub() subn() split()
In this part, we concentrate on the following three functions:
match() fullmatch() search()
All three functions are used for pattern matching, but their searching behaviour is different.
match() │ └── Checks only at the beginning fullmatch() │ └── Checks the complete target string search() │ └── Searches anywhere in the target string
Understanding this difference is very important when developing validation and pattern-matching applications.
The match() Function
The match() function is used to check the given pattern at the beginning of the target string.
Simple Definition
match() checks whether the target string starts with the specified Regular Expression pattern.
Syntax
re.match(pattern, string)
Example
re.match("in", "india")
Here Python checks whether "india" starts with "in".
How match() Works
Target String "india" │ ▼ Beginning of String │ ▼ Check Pattern "in" │ ▼ i n d i a └─┘ in │ ▼ Match Successful
If the pattern is available at the beginning, match() returns a Match Object. If the pattern is not available at the beginning, it returns None.
Return Value
| Condition | Return Value |
|---|---|
| Pattern is found at the beginning | Match Object |
| Pattern is not found at the beginning | None |
Once we get the Match Object, we can use methods such as:
start() end() group()
match() Demo Program
Enter a pattern and check whether it is available at the beginning of the target string "abcdefgh". Two runs are shown below — one successful and one unsuccessful.
match() Program Explanation and Flow
Step 1: Import the re module.
import re
Step 2: Read the Regular Expression from the user.
s = input("Enter pattern to check: ")
Step 3: Apply match().
m = re.match(s, "abcdefgh")
The target string is:
abcdefgh
match() checks only from index 0.
If the user enters abc, the target begins with abc:
a b c d e f g h 0 1 2 3 4 5 6 7 └───┘ abc
Therefore:
m.start() = 0 m.end() = 3 m.group() = abc
If the user enters bcd, then bcd exists in the target, but it does not start at index 0.
a b c d e f g h └───┘ bcd
Hence match() returns None.
Execution Flow
Start
│
▼
import re
│
▼
Read Pattern
│
▼
Target = "abcdefgh"
│
▼
re.match(pattern, target)
│
▼
Check Pattern Only
at Beginning
│
▼
Is Match Available?
│
┌┴─────────────┐
│ │
Yes No
│ │
▼ ▼
Match Object None
│ │
▼ ▼
Print Start Print
and End "Not Available"
│ │
└──────┬───────┘
▼
End
Important Point
match() does not search the complete string. Consider:
Target = "abcdefgh" Pattern = "def"
The pattern exists in the middle of the target:
a b c d e f g h
└───┘
def
But:
re.match("def", "abcdefgh")
returns None, because def is not present at the beginning.
The fullmatch() Function
The fullmatch() function is used to check whether the entire target string matches the given Regular Expression.
Simple Definition
fullmatch() succeeds only when the complete target string satisfies the specified pattern.
Syntax
re.fullmatch(pattern, string)
Example
re.fullmatch("abcdefgh", "abcdefgh")
This succeeds because the complete target matches the pattern.
How fullmatch() Works
Consider:
Pattern = "abcdefgh" Target = "abcdefgh"
Pattern : a b c d e f g h
│ │ │ │ │ │ │ │
Target : a b c d e f g h
The entire target matches, so:
Match Successful
But if:
Pattern = "abc" Target = "abcdefgh"
only a portion matches:
a b c d e f g h └───┘ abc
That is not sufficient for fullmatch().
Return Value
| Condition | Return Value |
|---|---|
| Entire target string matches | Match Object |
| Only part matches or no match | None |
fullmatch() Demo Program
Enter a pattern and check whether the complete target string "abcdefgh" matches it. Two runs are shown below — one successful and one unsuccessful.
fullmatch() Program Explanation and Flow
The important statement is:
m = re.fullmatch(s, "abcdefgh")
The target is:
abcdefgh
If the user enters abcdefgh, the complete string matches:
Pattern : abcdefgh
Target : abcdefgh
└──────┘
Full Match
Hence the output is:
Full String Matched
But if the user enters abc, only the beginning portion matches:
abcdefgh └─┘ abc
The remaining characters defgh are not covered by the pattern. Therefore fullmatch() returns None and the output is Full String not Matched.
Execution Flow
Start
│
▼
import re
│
▼
Read Pattern
│
▼
Target = "abcdefgh"
│
▼
re.fullmatch()
│
▼
Check Entire Target
Against Pattern
│
▼
Does Complete String Match?
│
┌┴──────────────┐
│ │
Yes No
│ │
▼ ▼
Match Object None
│ │
▼ ▼
Print Print
"Full String "Full String
Matched" not Matched"
│ │
└───────┬───────┘
▼
End
fullmatch() for Complete Validation
fullmatch() becomes especially useful for validation.
For example:
re.fullmatch("\\d{10}", "9876543210")
The pattern means:
\d{10}
│
▼
Exactly 10 digits
The complete target contains exactly ten digits, so the match succeeds.
This type of complete-string checking is useful when validating data such as:
- Mobile numbers
- Identifiers
- Registration numbers
- Other fixed-format strings
The search() Function
The search() function searches the target string for the first occurrence of the given Regular Expression.
Simple Definition
search() searches the target string and returns the first occurrence of the specified pattern.
Syntax
re.search(pattern, string)
Unlike match(), the pattern does not have to occur at the beginning.
How search() Works
Consider:
Target = "abcdefgh" Pattern = "def"
search() starts searching through the target:
a b c d e f g h
└───┘
def
The pattern starts at index 3. Therefore:
start() = 3 end() = 6 group() = def
search() returns the first successful Match Object.
Return Value
| Condition | Return Value |
|---|---|
| Pattern occurs somewhere in target | Match Object for first occurrence |
| Pattern does not occur | None |
search() Demo Program
Enter a pattern and search for its first occurrence in the target string "abcdefgh". Three runs are shown below.
search() Program Explanation and Flow
The important statement is:
m = re.search(s, "abcdefgh")
Suppose the user enters def. Python searches the target abcdefgh from left to right:
Index 0 → Pattern does not start here Index 1 → Pattern does not start here Index 2 → Pattern does not start here Index 3 → "def" found
Once the first match is found, search() returns its Match Object. Therefore:
m.start() = 3 m.end() = 6 m.group() = def
search() Finds Only the First Occurrence
This is an important difference between search() and functions such as finditer(). Consider:
Target = "ababab" Pattern = "ab"
The pattern occurs three times:
ab ab ab ↑ First
But:
re.search("ab", "ababab")
returns only the first Match Object:
start() = 0 end() = 2 group() = ab
If we want all occurrences, finditer() or findall() is more suitable.
Execution Flow
Start
│
▼
import re
│
▼
Read Pattern
│
▼
Target = "abcdefgh"
│
▼
re.search()
│
▼
Search from Left
to Right
│
▼
Pattern Found?
│
┌┴──────────────┐
│ │
Yes No
│ │
▼ ▼
Return First Return
Match Object None
│ │
▼ ▼
Print Start Print
and End "Not Available"
│ │
└───────┬───────┘
▼
End
Same Pattern with match(), fullmatch() and search()
Let us use the same pattern with all three functions and observe the different results.
Example 1 - Pattern "def"
Consider:
Target = "abcdefgh" Pattern = "def"
Using match():
re.match("def", "abcdefgh")
Result: None — because def is not at the beginning.
Using fullmatch():
re.fullmatch("def", "abcdefgh")
Result: None — because the complete target is not exactly def.
Using search():
re.search("def", "abcdefgh")
Result: Match Object — because def occurs somewhere inside the target.
Example 2 - Pattern "abc"
Consider:
Target = "abcdefgh" Pattern = "abc"
| Function | Result | Reason |
|---|---|---|
match() |
Success | abc is at the beginning |
fullmatch() |
Failure | abc does not cover the complete target |
search() |
Success | abc occurs in the target |
Example 3 - Complete Pattern
Consider:
Target = "abcdefgh" Pattern = "abcdefgh"
Now all three functions succeed:
| Function | Result |
|---|---|
match() |
Success |
fullmatch() |
Success |
search() |
Success |
Why?
match() → Pattern starts at beginning ✓ fullmatch() → Complete target matches ✓ search() → Pattern exists in target ✓
Complete Comparison Table and Memory Rule
The following table compares match(), fullmatch() and search() side by side.
| Feature | match() | fullmatch() | search() |
|---|---|---|---|
| Checks beginning | Yes | Not enough by itself | Can search there |
| Requires complete string match | No | Yes | No |
| Can find pattern in middle | No | No, unless whole pattern matches whole target | Yes |
| Returns Match Object on success | Yes | Yes | Yes |
| Returns None on failure | Yes | Yes | Yes |
| Returns first occurrence | At beginning only | Whole target only | Yes |
| Common use | Check beginning | Complete validation | Find first occurrence |
Easy Way to Remember
Target String
+-----------------------------------+
| a b c d e f g h |
+-----------------------------------+
match()
^^^^^^
Checks from START
fullmatch()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Entire String Must Match
search()
^^^^^^^^^
Can Find Pattern ANYWHERE
Remember:
match() → START fullmatch() → FULL search() → ANYWHERE, FIRST MATCH
Match Object Methods and the None Check
When any of these functions succeeds, we receive a Match Object. The important methods are:
| Method | Purpose |
|---|---|
start() |
Returns the starting index |
end() |
Returns the index immediately after the match |
group() |
Returns the matched string |
Example:
m = re.search("def", "abcdefgh")
Then:
m.start() → 3 m.end() → 6 m.group() → def
Why Check m != None?
Consider:
m = re.search("xyz", "abcdefgh")
There is no match, so m = None. If we immediately write m.start(), Python cannot call start() on None.
Therefore, we first check:
if m != None:
and only then access:
m.start() m.end() m.group()
A common Python style is also:
if m:
because a successful Match Object is truthy while None is falsy.
Combined Demo Program
The following program applies match(), fullmatch() and search() to the same target and pattern, so the different results can be compared directly.
The target is abcdefgh and the pattern is def:
match()fails becausedefdoes not begin at index0→None.fullmatch()fails because the entire target is not exactlydef→None.search()succeeds becausedefexists at indexes3to5→ returns the first Match Object.
search() │ ▼ Start = 3 End = 6 Group = def
Complete Execution Flow
The following diagram shows how the pattern and the target string flow through all three functions.
Pattern
│
▼
Target String
│
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
match() fullmatch() search()
│ │ │
▼ ▼ ▼
Check Beginning Check Entire Search Anywhere
│ Target String │
▼ ▼ ▼
Success? Success? First Match?
│ │ │
┌──┴──┐ ┌──┴──┐ ┌──┴──┐
│ │ │ │ │ │
Yes No Yes No Yes No
│ │ │ │ │ │
▼ ▼ ▼ ▼ ▼ ▼
Match None Match None Match None
Object Object Object
│ │ │
└──────────────┼──────────────┘
▼
Use start(), end(),
group()
Quick Revision
match() │ ▼ Pattern must match at the BEGINNING fullmatch() │ ▼ Pattern must match the COMPLETE STRING search() │ ▼ Pattern can occur ANYWHERE │ ▼ Returns FIRST occurrence
On success, all three return a Match Object. On failure, all three return None.
Which Function Should We Use?
Depending on the requirement, we should choose the appropriate function:
| Requirement | Recommended Function |
|---|---|
| Check whether pattern exists at beginning | match() |
| Check whether entire string follows pattern | fullmatch() |
| Find first occurrence anywhere | search() |
| Find all occurrences as Match Objects | finditer() |
| Find all matching values | findall() |
The easy memory rule is:
match() → beginning fullmatch() → entire string search() → first occurrence anywhere
- match() checks the pattern only at the beginning of the target string and returns a Match Object on success
- fullmatch() succeeds only when the complete target string satisfies the pattern
- search() searches the target string and returns the first occurrence of the pattern anywhere in it
- All three functions return a Match Object on success and None on failure
- A Match Object provides start(), end() and group(), and these methods must be called only when a match exists