Python Regex
Find and validate text patterns with Python regex.
When working with text, you often need to search for specific words, validate user input, replace text, or extract useful information from a large amount of data. For example, you may want to check whether an email address is valid, find all phone numbers in a document, or replace every occurrence of a word.
Python provides a powerful feature called Regular Expressions, commonly known as Regex, to perform these tasks efficiently.
In this lesson, you will learn what Regex is, how to use Python's built-in re module, and the most commonly used Regex functions and patterns.
What is Regex?
A Regular Expression (Regex) is a sequence of characters that defines a search pattern. Instead of searching for exact text only, Regex allows you to search for text that follows a specific pattern. For example, instead of searching for one particular phone number, you can search for any sequence of ten digits.
Python provides built-in support for Regex through the re module.
import reOnce imported, you can use different functions to search, match, replace, and split text.
The search() Function
The search() function looks for the first match of a pattern anywhere in the string.
import re
text = "Welcome to Python Programming"
result = re.search("Python", text)
print(result)Output
<re.Match object ...>If the pattern is found, search() returns a match object. Otherwise, it returns None.
The match() Function
The match() function checks only the beginning of a string.
import re
text = "Python is easy"
result = re.match("Python", text)
print(result)Because the text starts with Python, a match is found. If the word appeared later in the string, match() would return None.
The findall() Function
The findall() function returns all matches as a list.
import re
text = "Python is popular. Python is easy."
result = re.findall("Python", text)
print(result)Output
['Python', 'Python']This function is useful when you need every occurrence of a pattern.
The sub() Function
The sub() function replaces matching text with new text.
import re
text = "I like Java."
new_text = re.sub("Java", "Python", text)
print(new_text)Output
I like Python.This is useful when cleaning or updating text.
The split() Function
The split() function divides a string wherever a pattern matches.
import re
text = "Apple,Banana,Orange"
items = re.split(",", text)
print(items)Output
['Apple', 'Banana', 'Orange']This is helpful when processing structured text.
Common Regex Symbols
Regex uses special characters to define flexible search patterns.
| Symbol | Meaning |
|---|---|
| . | Any single character |
| ^ | Start of a string |
| $ | End of a string |
| * | Zero or more occurrences |
| + | One or more occurrences |
| ? | Zero or one occurrence |
| [] | Matches one character from a set |
| | | OR operator |
| () | Groups patterns |
Learning these symbols allows you to create flexible search patterns.
Common Character Classes
| Pattern | Matches |
|---|---|
| \d | Any digit from 0 to 9 |
| \D | Any non-digit |
| \w | Letters, digits, and underscore |
| \W | Non-word characters |
| \s | Whitespace |
| \S | Non-whitespace |
import re
text = "Order123"
print(re.findall(r"d", text))Output
['1', '2', '3']The pattern \d finds every digit in the string.
Validating an Email
Regex is commonly used to check whether user input follows an expected format.
import re
email = "user@example.com"
pattern = r"^[w.-]+@[w.-]+.w+$"
if re.match(pattern, email):
print("Valid email")
else:
print("Invalid email")This example checks a common email shape. For production systems, validation requirements may be more detailed, and confirmation emails are still needed to verify ownership.
Why Use Raw Strings?
Regex patterns often contain backslashes. In Python, write patterns as raw strings by placing r before the opening quotation mark.
pattern = r"d+"Raw strings prevent Python from treating backslashes as ordinary escape sequences, making Regex patterns easier to read.
Real-World Uses of Regex
- Validating email address formats
- Checking phone number formats
- Searching log files
- Replacing unwanted words
- Extracting URLs from web pages
- Finding hashtags or usernames on social media
- Cleaning imported data
Because of its flexibility, Regex is widely used in web development, data processing, and automation.
Key Takeaways
- Regular Expressions help search, match, replace, and validate text using patterns.
- Python provides Regex support through the built-in re module.
- search() finds the first match anywhere in a string.
- match() checks only the beginning of a string.
- findall() returns every matching result as a list.
- sub() replaces matching text with new text.
- split() divides text wherever a pattern matches.
- Character classes such as \d, \w, and \s simplify pattern creation.
- Raw strings make Regex patterns easier to write and understand.
- Regex is a powerful tool for text processing, input validation, data cleaning, and automation in Python.