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
| Pattern | Meaning |
|---|---|
| \d | Any digit (0-9) |
| \D | Any non-digit |
| \w | Any word character (letters, digits, underscore) |
| \s | Any 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
remodule to work with regular expressions in Python search()finds the first match anywhere;match()only checks the startfindall()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