🔍 Python RegEx – Powerful Pattern Matching Made Easy | TechTown.in
Want to find phone numbers in a document? Validate emails? Clean messy data?
That’s where Regular Expressions (RegEx) in Python come in. Using the built-in re module, you can search, match, and manipulate strings with precision.
In this beginner’s guide, we’ll help you master Python RegEx step by step — no headaches, just clarity!
📦 What is re Module in Python?
The re module lets you work with regular expressions — patterns used to match character combinations in strings.
import re
🔍 Basic Pattern Matching with re.search()
import re
txt = "TechTown is amazing!"
match = re.search("amazing", txt)
if match:
print("Found!")
✅ re.search() looks for the first match anywhere in the string.
🔎 re.findall() – Get All Matches
txt = "Email: user@example.com, admin@example.com"
emails = re.findall(r"\S+@\S+", txt)
print(emails)
🎯 Output:
['user@example.com', 'admin@example.com']
🧹 re.sub() – Replace Using Pattern
txt = "Python is cool"
new_txt = re.sub("cool", "awesome", txt)
print(new_txt) # Python is awesome
🎯 Use this to clean or modify text dynamically.
🧪 re.split() – Split by Pattern
txt = "name|email|age"
parts = re.split(r"\|", txt)
print(parts) # ['name', 'email', 'age']
✅ Like .split() but powered by RegEx patterns.
✨ Special RegEx Symbols
| Symbol | Meaning | Example |
|---|---|---|
. | Any character (except newline) | "a.b" matches “a_b”, “a9b” |
^ | Start of string | ^Hello matches “Hello World” |
$ | End of string | world$ matches “Hello world” |
* | 0 or more repetitions | "lo*" matches “l”, “lo”, “loo” |
+ | 1 or more repetitions | "lo+" matches “lo”, “loo”, but not “l” |
{} | Exact count | "a{3}" matches “aaa” |
[] | Set of characters | "[a-c]" matches “a”, “b”, or “c” |
\d | Digit | "My number is \d\d\d" matches 3 digits |
\w | Word character (a-z, 0-9, _) | Useful for matching usernames |
\s | Whitespace | Tabs, spaces, newlines |
🎯 Real-Life Use Case – Validate Email Address
email = "user@example.com"
pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"
if re.match(pattern, email):
print("Valid email")
else:
print("Invalid")
🧠 Best Practices
- Use raw strings (
r"text") to avoid escaping backslashes - Test patterns on regex101.com
- Keep patterns readable and modular for maintainability
📝 Python RegEx Cheatsheet
| Function | Use Case |
|---|---|
re.search() | Find first match |
re.findall() | Return all matches |
re.sub() | Replace pattern with text |
re.split() | Split string by pattern |
re.match() | Match only from beginning |
🧪 Real-World Applications
- Email/Phone validation
- Web scraping
- Log analysis
- Form input cleaning
- Chatbot commands
🏁 Final Thoughts
With Python’s re module, regular expressions become a superpower for any developer working with text. It’s not just a tool — it’s a whole new way to think about string processing.
📘 Keep mastering Python magic at TechTown.in

