How to use regular expressions in Python

1 min readRegexAdvancedTextData Manipulation
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

In Python, you can use regular expressions (regex) with the re module.

Here are some basic regex operations in Python:

  1. search: Searches the string for a match to the regex pattern and returns a Match object if there is a match anywhere in the string.
import re

text = "The cat is cute."

match = re.search(r"cat", text)

if match:
    print("Match found!")
  1. findall: Returns a list containing all matches in the string as strings.
import re

text = "The cat is cute. The dog is friendly."

matches = re.findall(r"\w+", text)

print(matches)
# Output: ['The', 'cat', 'is', 'cute', 'The', 'dog', 'is', 'friendly']
  1. sub: Replaces all occurrences of the regex pattern in the string with a specified replacement.
import re

text = "The cat is cute. The dog is friendly."

new_text = re.sub(r"\bcat\b", "dog", text)

print(new_text)
# Output: 'The dog is cute. The dog is friendly.'
  1. split: Splits the string by the occurrences of the regex pattern.
import re

text = "The cat is cute. The dog is friendly."

words = re.split(r"\s+", text)

print(words)
# Output: ['The', 'cat', 'is', 'cute.', 'The', 'dog', 'is', 'friendly.']

These are just some of the basic operations you can perform with regex in Python. You can find more information in the Python documentation: https://docs.python.org/3/library/re.html

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months πŸš€

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. πŸ“š

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.