</> Code Editor

Python Regular Expressions Exercises


1/20

Python Regular Expressions Practice Questions

Correct
0%

Which of the following patterns will match any 3-letter string consisting of lowercase letters only?


This question tests your understanding of basic regex, anchors, and quantifiers.

  • Option 1: Correct. ^[a-z]{3}$ means:
    • ^ → start of string
    • [a-z] → any lowercase letter
    • {3} → exactly 3 letters
    • $ → end of string
  • This pattern ensures that only strings with exactly 3 lowercase letters match.
  • Option 2: Matches 3 consecutive lowercase letters anywhere in the string, so strings with extra characters will also match.
  • Option 3: Matches 2–4 letters, not exactly 3.
  • Option 4: Matches 3 or more letters; strings longer than 3 will also match.

Example usage:

import re

pattern = r'^[a-z]{3}$'
print(bool(re.match(pattern, 'cat')))  # True
print(bool(re.match(pattern, 'cats'))) # False
print(bool(re.match(pattern, 'ca')))   # False

Tip: Use ^ and $ anchors to ensure the whole string matches the pattern exactly. Without anchors, regex may match substrings.

Quick Recap of Python Regular Expressions Concepts

If you are not clear on the concepts of Regular Expressions, you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.

What Are Regular Expressions?

A regular expression is a sequence of characters that defines a search pattern. Instead of checking text manually with multiple conditions or string functions, regex allows you to describe the structure of the text you want to find.

Regular expressions in Python are extremely useful for tasks such as:

  • Extracting all numbers from a string
  • Validating email addresses
  • Finding specific word patterns
  • Splitting text using multiple delimiters
  • Replacing multiple text patterns efficiently

Python provides regex support through the built-in re module:

import re

Common Regex Functions in Python

Python's re module provides several useful functions to search, match, replace, and split text using regular expressions.

Function Description
re.search() Finds the first occurrence of the pattern anywhere in the string.
re.match() Checks whether the pattern matches from the beginning of the string.
re.findall() Returns a list of all non-overlapping matches.
re.finditer() Returns an iterator containing match objects for all matches.
re.sub() Replaces matched patterns with the specified replacement text.
re.split() Splits a string based on the given regex pattern.
re.compile() Precompiles a pattern for better performance when used multiple times.

Basic Regex Syntax and Meaning

Regular expressions use special symbols and sequences to represent different kinds of text patterns. Below are some of the most commonly used regex components in Python.

Pattern Meaning
. Matches any single character except newline.
\d Matches any digit (0–9).
\w Matches any word character (letters, digits, underscore).
\s Matches any whitespace character.
^ Matches the start of a string.
$ Matches the end of a string.
* Matches 0 or more repetitions.
+ Matches 1 or more repetitions.
? Matches 0 or 1 repetition.
{m,n} Matches the previous pattern between m and n times.
[] Defines a character set.
| Acts as an OR operator.
() Groups patterns together.

Why Use Regular Expressions?

Regular expressions are extremely powerful tools for working with text. They allow you to search, extract, validate, and manipulate patterns in strings with precision. Instead of manually checking each character or writing lengthy conditional logic, regex provides a compact and expressive way to describe complex text rules.

  • Find patterns quickly: Search for words, digits, symbols, or custom text patterns.
  • Validate inputs: Email formats, phone numbers, IDs, passwords, etc.
  • Extract information: Pull specific details from logs, forms, or documents.
  • Replace or clean text: Remove unwanted characters, format data, or sanitize input.
  • Efficient text parsing: Handle large datasets, files, and structured/unstructured text.

In Python, the re module makes working with regular expressions simple and efficient. With just a few expressions, you can accomplish tasks that would otherwise require many lines of code.

Basic Syntax and Metacharacters

Regular expressions work through a collection of special characters known as metacharacters. These characters help define search patterns and give regex its power. Understanding these basics is essential before working on more advanced patterns.

Metacharacter Meaning Example
. Matches any character except newline a.c matches abc, a1c, a-c
^ Matches the start of a string ^Hello matches any string starting with “Hello”
$ Matches the end of a string world$ matches any string ending with “world”
* Matches 0 or more repetitions go* matches g, go, goo...
+ Matches 1 or more repetitions go+ matches go, goo...
? Matches 0 or 1 repetition (optional) colou?r matches color and colour
[] Character set [abc] matches a, b, or c
() Grouping or capturing (abc)+ matches repeated “abc”
| Alternation (OR) cat|dog matches cat or dog
\ Escape special characters \. matches a literal dot(.)

These metacharacters form the foundation of almost all regular expression patterns. In the following sections, you will see how they work together inside Python code.

Using Regular Expressions in Python (re Module)

Python provides a powerful built-in module named re that allows you to work with regular expressions. This module includes functions to search, match, split, substitute, and find all occurrences of patterns within strings. Below are the most commonly used functions in the re module.

Function Description Example (Scrollable Code)
re.search() Searches for the first occurrence of a pattern
import re

text = "Welcome to Python"
result = re.search("Python", text)
print(result)
re.findall() Returns all matches as a list
import re

text = "cat, dog, cat, tiger"
matches = re.findall("cat", text)
print(matches)  # ['cat', 'cat']
re.match() Checks only the beginning of a string
import re

text = "Python is fun"
result = re.match("Python", text)
print(result)
re.split() Splits a string by the matched pattern
import re

text = "one-two-three"
parts = re.split("-", text)
print(parts)
re.sub() Replaces pattern occurrences with another string
import re

text = "blue sky, blue ocean"
result = re.sub("blue", "green", text)
print(result)

These functions cover almost all regular expression use cases in Python. In the upcoming sections, we will explore more advanced usage, pattern typing, special sequences, and practical examples.

Character Classes in Regular Expressions

Character classes allow you to match a specific set or range of characters. They are written inside square brackets []. Instead of writing long OR conditions, character classes provide a shorter and more flexible way to define which characters are acceptable in a match.

1. Basic Character Class

Matches any one character from the specified set.

import re

pattern = r"[abc]"
text = "apple"
result = re.findall(pattern, text)
print(result)   # ['a']

2. Character Range

Use a hyphen - to define a range of characters.

import re

pattern = r"[a-z]"
text = "Python3"
result = re.findall(pattern, text)
print(result)   # ['y', 't', 'h', 'o', 'n']

3. Negated Character Class

Use ^ inside the brackets to match anything except the defined characters.

import re

pattern = r"[^0-9]"
text = "A1B2C3"
result = re.findall(pattern, text)
print(result)   # ['A', 'B', 'C']

4. Multiple Character Groups

You can combine ranges and characters in the same class.

import re

pattern = r"[A-Za-z0-9]"
text = "Hello#2024!"
result = re.findall(pattern, text)
print(result)

Common Uses

  • Matching alphabet characters

  • Detecting digits
  • Filtering out unwanted characters
  • Validating usernames, filenames, and identifiers

Character classes are one of the most fundamental features of regex. They make matching flexible, readable, and powerful for building text filters, validators, and pattern recognizers.

Predefined Character Classes in Regular Expressions

Regular expressions provide several built-in shorthand character classes that make pattern matching cleaner and easier. These shortcuts match common types of characters such as digits, letters, or whitespace, saving you from manually writing long ranges.

Pattern Description Example Match
\d Matches any digit (0–9) “7” in "Grade7"
\D Matches any non-digit “G” in "G7"
\w Matches letters, digits, and underscore “A” or “t” in "A_10"
\W Matches any non-alphanumeric character “#” in "A#1"
\s Matches whitespace (space, tab, newline) space in "Hello World"
\S Matches any non-whitespace “H” in "Hello"
\b Word boundary Match before “Python” in "Python code"
\B Not a word boundary Middle of a word

Example: Extracting Digits from a String

import re

pattern = r"\d+"
text = "Order ID: 45829, Amount: $1200"
result = re.findall(pattern, text)
print(result)  # ['45829', '1200']

Example: Matching Words Only

import re

pattern = r"\w+"
text = "Hello World_2024!"
result = re.findall(pattern, text)
print(result)  # ['Hello', 'World_2024']

Example: Finding Whitespace

import re

pattern = r"\s"
text = "New York City"
result = re.findall(pattern, text)
print(result)  # [' ', ' ']

Predefined character classes make regex easier, cleaner, and more readable. They cover the majority of common text-matching needs and work in almost all data-processing tasks.

Anchors: Matching Start and End of Strings

Anchors match positions, not characters. They help validate formats such as IDs, emails, and fixed-pattern inputs.

Anchor Meaning Example Use
^ Matches the start of the string Check if text begins with a word
$ Matches the end of the string Ensure a string ends with digits

Example: Must Start with a Capital Letter

import re

pattern = r"^[A-Z]"
print(bool(re.match(pattern, "Boston")))   # True
print(bool(re.match(pattern, "boston")))   # False

Example: Must End with Three Digits

import re

pattern = r"\d{3}$"
print(bool(re.search(pattern, "Report_202")))  # True
print(bool(re.search(pattern, "Report_20A")))  # False
 


About This Exercise: Python – Regular Expressions

Welcome to Solviyo’s Python – Regular Expressions exercises, a carefully designed collection that helps you understand how pattern matching works in Python. Regular expressions (often called regex) are powerful tools that allow you to search, validate, and manipulate text with precision. These exercises are meant to guide you through the core ideas behind regex so you can use them confidently in real-world Python projects.

If you ever need a short refresher before solving the exercises, feel free to expand the Quick Recap section. It gives you a fast summary of the essential concepts so you can jump into the questions with clarity.

What You Will Learn

In this exercise set, you’ll work through the most important elements of Python regular expressions, including:

  • How patterns work and how to write them effectively using special symbols and character classes.
  • Using functions like match(), search(), findall(), and sub() from Python’s re module to process and transform text.
  • Understanding anchors, quantifiers, groups, and ranges to create flexible and powerful regex patterns.
  • Applying regular expressions to validate input, extract information, and clean up messy data.

Each exercise includes a clear answer and explanation, helping you understand not just the “what,” but also the “why” behind every solution. This makes the learning process smoother and helps you develop a strong intuition for pattern-based problem solving.

Why Regular Expressions Matter in Python

Regex is one of those skills that becomes more valuable the deeper you go into programming. Whether you’re analyzing text, cleaning data, building automation scripts, processing logs, or validating user input, regular expressions save time and make your code more efficient. Having a good grasp of regex strengthens your ability to solve problems quickly, especially in data-heavy work, backend development, or tasks that involve parsing large text files.

We created these exercises to make regex feel less intimidating and more practical. By practicing real use-cases instead of memorizing patterns, you’ll develop a hands-on understanding that sticks with you.

Start Practicing Python Regular Expressions

These Python regex exercises will help you build confidence step by step. Take your time, explore the patterns, and use the Quick Recap whenever you need a quick reminder. By the time you work through all the questions, you’ll be ready to apply regular expressions to real Python problems with accuracy and ease.