Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟡 Advanced Python  ·  Lesson 23

Regular Expressions in Python

In this lesson: Python regular expressions with the re module — search, match, findall, sub — email and phone patterns with output.

What is a Regular Expression?

A regular expression (regex) is a pattern used to search, match or extract text. Python's re module powers it. Regex is great for checking emails, phone numbers, PIN codes and more.

Common Patterns

PatternMatches
\dany digit (0-9)
\wletter, digit or underscore
\sa space
.any character
+one or more
*zero or more
{n}exactly n times

re Functions

  • re.search() — find the first match anywhere.
  • re.findall() — return all matches as a list.
  • re.match() — match only at the start.
  • re.sub() — replace matches.

Program 1: Find a Pattern

Python – find.py
import re
text = "My roll number is 42"
match = re.search(r"\d+", text)
if match:
    print("Found number:", match.group())
Found number: 42

r"\d+" means "one or more digits". .group() returns the matched text.

Program 2: Validate an Email

Python – email.py
import re
pattern = r"^[\w.]+@[\w]+\.[a-z]{2,}$"
email = input("Enter email: ")
if re.match(pattern, email):
    print("Valid email")
else:
    print("Invalid email")
Enter email: aman@gmail.com Valid email
  • [\w.]+ = name part; @ literal; [\w]+ = domain.
  • \.[a-z]{2,} = a dot then at least 2 letters (com, in...).

Program 3: Extract All Phone Numbers

Python – phones.py
import re
text = "Call 9876543210 or 9123456780 today"
numbers = re.findall(r"\d{10}", text)
print("Phone numbers:", numbers)
Phone numbers: ['9876543210', '9123456780']

\d{10} matches exactly 10 digits; findall returns every match as a list.

Common Mistakes

  • Forgetting the r"..." raw string — backslashes get misread.
  • Using match (start only) when you meant search (anywhere).
  • Over-complicating patterns — start simple and test.

Practice Tasks

  1. Check if a string contains any digit.
  2. Validate a 6-digit PIN code.
  3. Extract all words starting with a capital letter.
  4. Replace all spaces in a string with hyphens using re.sub.

Summary

  • Regex matches text patterns using the re module.
  • Key patterns: \d digit, \w word char, + one-or-more, {n} exactly n.
  • Functions: search, findall, match, sub. Always use raw strings r"...".

Frequently Asked Questions

What is the difference between re.match() and re.search()?
re.match() checks only at the start of the string; re.search() looks for the pattern anywhere.
Why are regex patterns written as raw strings like r"\d+"?
In a raw string backslashes are not treated as escape characters by Python, so the pattern reaches the regex engine unchanged.
What does \d+ match?
One or more digits, such as 7, 42 or 2026.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicDate and Time Handling Your progress: 23 / 66 (35%) · Lesson 24 / 66 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free