Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to Python Notes
Topic #13

Regex in Python

What Is Regex?

Regular expressions (regex) are patterns used to search, match, and manipulate text. Python's built-in re module provides full regex support.

import re

Basic Matching

import re

text = "My phone number is 9818523125"
match = re.search(r"\d+", text)
if match:
    print(match.group())   # 9818523125

Common Regex Patterns

PatternMeaning
\dAny digit (0-9)
\DAny non-digit
\wAny word character (letters, digits, underscore)
\sAny whitespace character
.Any character except newline
+One or more occurrences
*Zero or more occurrences
?Zero or one occurrence
^ / $Start / end of string

Key re Functions

re.match() — checks the start of the string

result = re.match(r"Hello", "Hello World")
print(result.group() if result else "No match")   # Hello

re.search() — finds the pattern anywhere

result = re.search(r"World", "Hello World")
print(result.group())   # World

re.findall() — returns all matches as a list

text = "Emails: aman@test.com, riya@test.com"
emails = re.findall(r"[\w.]+@[\w.]+", text)
print(emails)   # ['aman@test.com', 'riya@test.com']

re.sub() — replaces matches with new text

text = "Call me at 9818523125"
masked = re.sub(r"\d", "*", text)
print(masked)   # Call me at **********

re.split() — splits a string using a pattern

text = "apple, banana; cherry  mango"
parts = re.split(r"[,;\s]+", text)
print(parts)   # ['apple', 'banana', 'cherry', 'mango']

Real-World Example: Validating an Email

import re

def is_valid_email(email):
    pattern = r"^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$"
    return bool(re.match(pattern, email))

print(is_valid_email("student@codingnowai.in"))   # True
print(is_valid_email("not-an-email"))               # False

Key Takeaways

  • Import the re module to work with regular expressions in Python
  • search() finds the first match anywhere; match() only checks the start
  • findall() returns every match; sub() replaces matches; split() breaks text apart by a pattern
  • Prefix pattern strings with r (e.g. r"\d+") to avoid escape-character issues

Want to go beyond the notes?

Join CodingNow's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →