re.search() function in Python is used to search for the first occurrence of a regular expression pattern within a string. It scans the entire string and returns a Match object if a match is found; otherwise, it returns None.
Syntax
re.search( pattern, string, flags=0 )
Parameters:
- pattern: Regular expression pattern to search for.
- string: String in which the pattern is searched.
- flags: Modifiers that control matching behavior, such as case-insensitive matching. The default value is 0.
Return Value:
- Match object: Returned when the pattern is found. It provides methods to access the matched text and its position.
- None: Returned when no match is found.
Example 1: Using re.search() to Find a Word.
import re
s = "Python is a popular programming language"
res = re.search(r"popular", s)
if res:
print("Pattern found")
else:
print("Pattern not found")
Output
Pattern found
Explanation:
- re module is imported to perform regular expression matching.
- Popular pattern is searched throughout the string.
- Since the word exists, re.search() returns a Match object and the condition prints Pattern found.
Example 2: Finding Next Number in a String
import re
s = "I have 25 books and 10 notebooks"
res = re.search(r"\d+", s)
if res:
print(res.group())
print(res.start())
print(res.end())
else:
print("No number found")
Output
25 7 9
Explanation:
- \d+ pattern matches one or more consecutive digits.
- group() method returns the matched number, while start() and end() provide its starting and ending indices.
- Search stops at the first matching sequence, which is 25.
Example 3: Using re.search() with Flags
import re
s = "Python is an EASY language"
res = re.search(r"easy", s, re.IGNORECASE)
if res:
print(res.group())
else:
print("Pattern not found")
Output
EASY
Explanation:
- Pattern easy is searched in the given string.
- re.IGNORECASE flag enables matching regardless of uppercase or lowercase letters.
- group() method returns the actual matched text, preserving its original capitalization.