Template request | Bug report | Generate Data Product
Tags: #regex #python #snippet #operations
Author: Florent Ravenel
Description: This notebook demonstrates how to match a pattern in a string using re.search()
and re.match()
. The main difference between re.search()
and re.match()
lies in how they apply pattern matching to the input string. re.search()
scans the entire input string and returns the first occurrence of a pattern match, regardless of its position within the string. On the other hand, re.match()
only checks for a pattern match at the beginning of the string.
To start, we recommand you to test your regular expression using this website: https://regex101.com/
References:
import re
pattern
: the email address to be checkedinput_string
: the email address to be checked
pattern = "\d+"
input_string = "Temperature: 0°C"
search_result = re.search(pattern, input_string)
search_result
match_result = re.match(pattern, input_string)
match_result
When we use re.match() with the same pattern, it fails to find a match because the pattern is only checked at the beginning of the string. Since "0" is not at the beginning, re.match() returns no match.
if search_result:
print("Search Result:", search_result.group())
else:
print("No match found with re.search()")
if match_result:
print("Match Result:", match_result.group())
else:
print("No match found with re.match()")