Skip to main content
  1. Notes/
  2. Python 🐍/

πŸ”Ž Regular Expressions (Regex) in Python | Lesson 17

Python Progmramming Course
Table of Contents
Python - This article is part of a series.
Part 17: This Article

πŸ”Ž Regular Expressions (Regex) in Python
#

Regular expressions are powerful tools to search, match, and manipulate text using patterns. They help you find patterns in strings like emails, phone numbers, or specific words. Python’s re module makes working with regex easy! Let’s learn the basics step-by-step! ✨


What is a Regular Expression? πŸ€”
#

It’s a special sequence of characters that describe a search pattern. For example, you could use regex to find all email addresses in a document or validate user input.


1. Importing the re Module 🧩
#

import re

2. Basic Regex Functions βš™οΈ
#

FunctionDescriptionExample
re.search()Search for a pattern in a stringFinds first match
re.findall()Find all matches in a stringReturns all matched substrings
re.match()Matches pattern at start of stringChecks only the beginning
re.sub()Replace matched parts with new textSubstitute text

3. Simple Patterns πŸ“
#

PatternMeaningExample
.Any character except newlinea.c matches ‘abc’
\dDigit (0-9)\d\d matches ‘42’
\wWord character (letters, digits, _)\w+ matches ‘Hello’
+One or more repetitionsa+ matches ‘aaa’
*Zero or more repetitionsa* matches ‘’, ‘a’, ‘aaaa’
?Optional (0 or 1)ca?t matches ‘cat’ or ‘ct’

4. Example: Find All Numbers in a Text
#

text = "I have 2 apples and 15 bananas."
numbers = re.findall(r'\d+', text)
print(numbers)  # ['2', '15']

5. Example: Validate an Email Address
#

email = "student@example.com"
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'

if re.match(pattern, email):
    print("Valid email!")
else:
    print("Invalid email!")

6. Replacing Text
#

Replace all vowels in a text with *:

text = "Hello World"
new_text = re.sub(r'[aeiouAEIOU]', '*', text)
print(new_text)  # H*ll* W*rld

Practice Questions with Solutions πŸ†
#

  1. Extract all words that start with “py” from a sentence.
  2. Validate if a phone number is in the format xxx-xxx-xxxx.
  3. Replace all whitespace in a string with underscores (_).

Mini Project: Extract Dates from Text πŸ“…
#

Find all dates in the format dd-mm-yyyy from a paragraph.

text = "John was born on 12-05-1990, and his sister on 25-12-1995."
dates = re.findall(r'\b\d{2}-\d{2}-\d{4}\b', text)
print("Dates found:", dates)

Checklist for This Chapter βœ…
#

  • Imported and used Python’s re module
  • Used basic regex functions (search, findall, match, sub)
  • Understood common regex symbols and patterns
  • Performed text searching, matching, and replacing with regex

Regular expressions are a fantastic skill for text processing, data validation, and scraping. Keep practicing and soon you’ll write complex pattern searches with ease! πŸŽ‰

Aryan
Author
Aryan
A little bit about you
Python - This article is part of a series.
Part 17: This Article

Related

⏰ Working with Date and Time in Python | Lesson 16
Python Progmramming Course
🎬 Strings in Python | Lesson 04
Python Progmramming Course
πŸ—οΈ Object-Oriented Programming (OOP) Concepts in Python | Lesson 15
Python Progmramming Course
πŸ‘Ά Python Basics | Lesson 02
Python Progmramming Course
πŸ“„ File Handling in Python | Lesson 14
Python Progmramming Course
πŸ“‹ Lists in Python | Lesson 05
Python Progmramming Course