Python Regex: Search, Match, and Replace Tutorial

 

 

Python Regex: Search, Match, and Replace Tutorial

🔍 Introduction

Regular expressions (regex) are a powerful way to perform pattern matching and text processing in Python.
They allow you to efficiently search, match, and replace parts of strings using a concise syntax.
This tutorial is designed to give you a practical understanding of how to use regex in Python using the built-in re module.

🎯 Objective

By the end of this tutorial, you will be able to:

  • Understand how to import and use the re module
  • Search for patterns within strings
  • Match specific string patterns
  • Replace text using regex patterns

💻 Python Code Example


import re

# Sample text
text = "Contact us at support@example.com or sales@example.org."

# Search for an email address
email_pattern = r'\b[\w.-]+@[\w.-]+\.\w+\b'
found_emails = re.findall(email_pattern, text)
print("Found emails:", found_emails)

# Match a word at the beginning of a string
match_result = re.match(r'Contact', text)
if match_result:
    print("Matched:", match_result.group())

# Replace email addresses with [email]
replaced_text = re.sub(email_pattern, '[email]', text)
print("Replaced text:", replaced_text)
    

🧠 Explanation

Let’s break down the program:

  • import re — Imports Python’s regex module.
  • re.findall() — Finds all substrings that match the email pattern.
  • re.match() — Tries to match the word “Contact” at the beginning of the string.
  • re.sub() — Replaces all detected email addresses with the string [email].

This script demonstrates core regex operations: searching with findall,
matching with match, and replacing with sub.

▶️ How to Run This Program

To run the program:

  1. Copy the code above into a file, e.g., regex_demo.py
  2. Open your terminal or command prompt
  3. Run the file with: python regex_demo.py

Make sure Python 3 is installed on your system.

 

One Reply to “Python Regex: Search, Match, and Replace Tutorial”

Leave a Reply

Your email address will not be published. Required fields are marked *