Python re.search
How does Python’s re.search() function work when searching for patterns in a string?
What does it return, and how can you use it to locate the first match of a regular expression efficiently?
Python’s re.search() function is part of the re module and is used to search for the first occurrence of a pattern within a string. Unlike re.match(), which only checks at the beginning of the string, re.search() scans the entire string to find a match anywhere.
Basic Usage
import re
result = re.search(r"cat", "The catalog has a cat")- If a match is found, re.search() returns a Match object
- If not found, it returns None
Accessing Match Details
If a match exists, you can extract useful information:
print(result.group()) # matched string
print(result.start()) # start position
print(result.end()) # end positionExample output:
cat
12
15 Pattern Options
You can also use:
- Character classes — e.g., [A-Z]
- Quantifiers — e.g., +, *, { }
Flags — case-insensitive search:
re.search(r"hello", "HELLO world", re.IGNORECASE) When to Use re.search()
- When the pattern can appear anywhere in the text
- For validation where placement doesn’t matter (e.g., checking if email contains “@”)
- To extract a specific substring in logs, files, or user input
In simple terms, re.search() is a flexible and powerful tool for pattern searching in Python, giving you detailed match information without limiting the match location to the beginning of the string.