The re.match() function returns only the first match of the pattern found in the given string.
Syntax
re.search(pattern, string, flags=0)
Parameters
- pattern(required): This is the regular expression pattern you want to search for in the string.
- string(required): The string in which you want to search for the pattern.
- flags(optional): Additional options that modify the behavior of the search, such as case-insensitive matching (re.IGNORECASE), multiline mode (re.MULTILINE), and others.
Return Value
It returns a Match object if there is a match, otherwise returns None.
Example 1: Finding a Word(substring)
import re
text = "Happy days bring happy ways."
match = re.search("happy", text)
if match:
print("Match found:", match.group())
else:
print("No match")
Output
Match found: happy
The match.group() retrieves the part of the string where the match was found.
Example 2: If no matches are found
import re
text = "Happy days bring happy ways."
match = re.search("Hey", text)
print(match)
Output
None
Example 3: Case-Insensitive Search
import re
text = "Happy days bring happy ways."
match = re.search("happy", text, re.IGNORECASE)
if match:
print("Match found:", match.group())
else:
print("No match")
Output
Match found: Happy
Example 4: Phone Number with a Specific Format
import re
# Define the text string to be searched
number = "Call me at 123-456-7890 tomorrow."
match = re.search(r'\d{3}-\d{3}-\d{4}', number)
# Check if the pattern was found
if match:
print("Phone number found:", match.group())
else:
print("No phone number found")
Output
Phone number found: 123-456-7890
In this example, we have used the pattern \d{3}-\d{3}-\d{4}, which searches for sequences of digits in the format xxx-xxx-xxxx.
\d represents any digit.
{3} indicates that the previous character (a digit in this case) should be repeated exactly 3 times.
– is a literal dash character.