🔍 Python Tutorial — Regular Expressions (re Module)

Introduction 🌟

Regular Expressions (RegEx or regex) are powerful patterns used for searching, matching, extracting, and manipulating text. Python provides the re module to work with regex.

Note

💡 Perfect for validation (email, phone, password)
💡 Excellent for text extraction and cleaning
💡 Used heavily in web scraping, NLP, log analysis

1. Importing the re Module 🧱

import_re.py

import re

2. Basic Functions in re Module 📘

FunctionPurpose
re.search()Find first match anywhere in string
re.match()Match only at the beginning
re.findall()Find all occurrences
re.finditer()Iterator of match objects
re.sub()Replace using regex
re.split()Split using regex

3. re.search() 🕵️

search_example.py

result = re.search("cat", "A black cat is here")
print(result.group())

✔ Searches anywhere in the string

4. re.match() 🎯

match_example.py

result = re.match("Hello", "Hello World")
print(result.group())

✔ Must match at the very beginning

5. re.findall() 📚

findall_example.py

print(re.findall("\d+", "My numbers: 10, 20, 30"))

✔ Extracts all numbers

6. re.sub() — Replacing Text 🛠️

sub_example.py

print(re.sub("cat", "dog", "I love cat and another cat"))

✔ Useful for data cleaning

7. re.split() — Splitting with Regex ✂️

split_example.py

print(re.split("[,; ]+", "a,b; c d"))

✔ Splits by multiple separators

8. Special Metacharacters 🎨

SymbolMeaning
.Any character
^Start of string
$End of string
*0 or more
+1 or more
?0 or 1
[]Character set
()Group
\dDigit
\wWord (letters, digits, _ )
\sWhitespace

9. Character Sets & Ranges 🔤

charset_example.py

re.findall("[A-Z]", "Hello PYTHON")  # ['H', 'P', 'Y', 'T', 'H', 'O', 'N']

10. Quantifiers 🔢

quantifier_example.py

re.findall("a{2,4}", "aaa aaaaa a")

✔ Matches "aa", "aaa", "aaaa"

11. Groups & Capturing 🎯

groups_example.py

result = re.search("(\w+)@(\w+)", "email@mail.com")
print(result.group(1))  # email
print(result.group(2))  # mail

✔ Useful for extracting structured data

12. Named Groups 🏷️

named_groups.py

pattern = r"(?P<user>\w+)@(?P<domain>\w+\.com)"
m = re.search(pattern, "sathish@gmail.com")

print(m.group("user"))
print(m.group("domain"))

13. Using Flags for Extra Power 🏴

FlagDescription
re.I / IGNORECASECase-insensitive
re.M / MULTILINE^ and $ match each line
re.S / DOTALLDot matches newline

flag_example.py

re.search("hello", "HELLO", re.I)

14. Real-World Example — Validate Email 📧

email_validation.py

email = "user123@mail.com"
pattern = r"^[\w.-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"

print(bool(re.match(pattern, email)))

15. Real-World Example — Extract Phone Numbers 📱

phone_extract.py

text = "Call me at 98765-43210 or 87654-32109"
print(re.findall("\d{5}-\d{5}", text))

16. Real-World Example — Remove Extra Spaces 🧹

clean_spaces.py

text = "Python     is   awesome"
clean = re.sub("\s+", " ", text)
print(clean)

17. finditer() — Detailed Matches 🎯

finditer_example.py

for m in re.finditer("\d+", "A1 B22 C333"):
    print(m.group(), "at", m.span())

Regex Cheat Sheet 📘

PatternMeaning
\dDigit
\DNon-digit
\wWord char
\WNon-word char
\sWhitespace
[abc]a or b or c
a{2,}2 or more a's
^startStarts with "start"
end$Ends with "end"

Best Practices 💡

  • ✔ Use raw strings → r"pattern"
  • ✔ Pre-compile patterns for speed (re.compile())
  • ✔ Keep regex simple and readable
  • ✔ Use named groups for clarity
  • ✔ Test patterns using online regex tools

Conclusion 🎉

>>“Regex turns messy text into structured data — mastering it unlocks powerful text-processing superpowers.” ✨

You now fully understand Regular Expressions (re module) in Python! Want the next topic? Try Lambda, OOP, File Handling, Generators, or Threading. Just tell me! 😊