← Back to Chapters

Python RegEx

? Python RegEx

⚡ Quick Overview

RegEx (Regular Expressions) are patterns used to search, match, and manipulate text. In Python, the re module provides powerful tools for working with these patterns so you can find substrings, validate input, and transform text efficiently.

Common use cases include validating email addresses, extracting specific data from logs, finding all occurrences of a word, and performing complex search-and-replace operations.

? Key Concepts

  • Pattern – A string that defines the search rule (the regular expression itself).
  • re module – Built-in Python module that contains regex functions.
  • Match object – Result returned by search/match functions when a pattern is found.
  • Raw string – A string prefixed with r that keeps backslashes as-is (e.g., r"\d+").
  • Metacharacters – Special characters with meanings, like \d, \w, ., *, ^, $.

? Syntax and Patterns

Some commonly used regex pieces in Python:

  • \d – Any digit (0–9)
  • \w – Any word character (letters, digits, underscore)
  • \s – Any whitespace (space, tab, newline)
  • ^ – Start of the string
  • $ – End of the string
  • .* – Any character (.) repeated zero or more times (*)

Always prefer using raw strings for patterns, for example: r"\d{3}-\d{2}-\d{4}". This avoids conflicts with Python's own escape sequences.

? Code Examples

? Basic search using re.search()
# Import the regular expressions module
import re

# Text in which we want to search for the pattern
text = "The rain in Spain"
# Search for the word 'Spain' in the text
match = re.search("Spain", text)

# If a match is found, print it
if match:
    print("Found:", match.group())
? Find all 3-letter words using re.findall()
import re

text = "cat bat rat mat"
matches = re.findall(r"\b\w{3}\b", text)
print(matches)  # ['cat', 'bat', 'rat', 'mat']
✂️ Replace text using re.sub()
import re

text = "I like cats"
new_text = re.sub("cats", "dogs", text)
print(new_text)  # I like dogs

? Live Output and Explanation

? Example walkthrough

Code: Basic search example with re.search().

What happens:

  1. The pattern "Spain" is searched inside the string "The rain in Spain".
  2. re.search() scans the entire string until it finds the first match.
  3. If a match is found, it returns a match object; otherwise it returns None.
  4. match.group() returns the actual matched text.

Expected output:

Found: Spain

? Tips and Best Practices

  • Use raw strings (r"pattern") to avoid escaping backslashes manually.
  • Test your regex patterns with online tools before using them in Python code.
  • Prefer re.findall() when you need to collect multiple matches at once.
  • Choose between re.search() and re.match() carefully:
    • re.match() checks only at the beginning of the string.
    • re.search() scans the whole string for the first match.

? Try It Yourself

  • Write a regex to extract all email addresses from a block of text using re.findall().
  • Use re.sub() to censor bad words by replacing them with ***.
  • Split a string into words but remove punctuation using re.split() and an appropriate pattern.
  • Create a pattern that matches a valid Indian mobile number (e.g., 10 digits, starting with 6–9).