Skip to content

Latest commit

 

History

History
74 lines (45 loc) · 2.59 KB

RegEx_Match_pattern.md

File metadata and controls

74 lines (45 loc) · 2.59 KB



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:

Input

Import libraries

import re

Setup Variables

  • pattern: the email address to be checked
  • input_string: the email address to be checked
pattern = "\d+"
input_string = "Temperature: 0°C"

Model

Match pattern using re.search()

search_result = re.search(pattern, input_string)
search_result

Match pattern using re.match()

match_result = re.match(pattern, input_string)
match_result

Output

Display 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()")