Python

 

 

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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)