Regular Expressions in Python
Learn how to search, match, validate and replace text patterns using Python regular expressions.
What is a Regular Expression?
A regular expression, also called a regex, is a pattern used to search and match text.
Python provides the built-in re module
for working with regular expressions.
Regular Expression Flow
Text
Input string that needs to be checked.
Regex Pattern
Pattern describes what we want to find.
Match Result
Python returns the matching result.
Importing the re Module
The re module provides functions for
working with regular expressions.
import re
re.search()
The re.search() function searches the
complete string for a matching pattern.
import re
text = "Python is easy to learn"
result = re.search("Python", text)
if result:
print("Pattern found")
Output:
Pattern found
Search When No Match Exists
import re
text = "Python is easy to learn"
result = re.search("Java", text)
if result:
print("Pattern found")
else:
print("Pattern not found")
Output:
Pattern not found
re.match()
The re.match() function checks whether
the pattern matches at the beginning of the string.
import re
text = "Python programming"
result = re.match("Python", text)
if result:
print("Match found")
else:
print("No match")
Output:
Match found
re.findall()
The re.findall() function returns all
matching values found in the string.
import re
text = "Python Java Python C#"
result = re.findall("Python", text)
print(result)
Output:
['Python', 'Python']
re.split()
The re.split() function splits a string
wherever the pattern is found.
import re
text = "Python,Java,C#"
result = re.split(",", text)
print(result)
Output:
['Python', 'Java', 'C#']
re.sub()
The re.sub() function replaces matching
text with another value.
import re
text = "Python is easy"
result = re.sub("easy", "powerful", text)
print(result)
Output:
Python is powerful
Common Regex Patterns
Digits
\d matches a digit.
\d
Word Character
\w matches a word character.
\w
Whitespace
\s matches whitespace.
\s
Finding Digits
import re
text = "My marks are 85"
result = re.findall(r"\d+", text)
print(result)
Output:
['85']
Finding Words
import re
text = "Python is easy"
result = re.findall(r"\w+", text)
print(result)
Output:
['Python', 'is', 'easy']
Example: Phone Number Validation
import re
phone = "9876543210"
pattern = r"^[0-9]{10}$"
if re.match(pattern, phone):
print("Valid phone number")
else:
print("Invalid phone number")
Output:
Valid phone number
Example: Email Validation
The following pattern uses \x40 to
represent the email separator character.
import re
email = "student@example.com"
pattern = r"^[\w.-]+\x40[\w.-]+\.\w+$"
if re.match(pattern, email):
print("Valid email")
else:
print("Invalid email")
Output:
Valid email
Example 📩🤓
The following example finds all numbers inside a text string.
import re
text = "Python course costs 30000 and lasts 5 months"
numbers = re.findall(r"\d+", text)
print(numbers)
Output:
['30000', '5']
Advantages of Regular Expressions
Search Text
Quickly find specific patterns in text.
Validation
Validate values such as emails and phone numbers.
Replace Text
Replace matching patterns using regex.
Best Practices
Keep Patterns Simple
Use a simple pattern when a simple pattern is enough.
Test Patterns
Test regular expressions with valid and invalid examples.
Use Raw Strings
Raw strings make regex patterns easier to write.
Common Mistakes
- Writing an incorrect regex pattern.
-
Forgetting to import the
remodule. -
Using
re.match()when a complete string search is required. - Not testing both matching and non-matching values.
Practice Programs
-
Search for a word inside a string using
re.search(). -
Find all numbers in a string using
re.findall(). -
Split a string using
re.split(). -
Replace a word using
re.sub(). - Validate a phone number using a regular expression.
- Validate an email address using a regular expression.
Summary
Regular expressions are patterns used to search, match,
validate and replace text. Python provides the
re module with functions such as
search(), match(),
findall(), split() and
sub(). Regular expressions are commonly
used for text processing and validation.