Regular Expressions

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — What are Regular Expressions?

A regular expression (or regex) is a special pattern used to search, match, and manipulate text. Think of it like a super-powered `in` operator. Instead of searching for an exact word, you can describe what the text looks like.

For example: "find all words that start with a capital letter" or "check if a string is a valid email". Python uses the `re` module for regex.

Exercise 2 — re.search() — Find a Match

`re.search(pattern, text)` scans the text and returns the first match, or `None` if nothing matches. Here, `\d+` means "one or more digits" and `.group()` returns the matched text.

import re text = "Pyrochu is level 25" match = re.search(r"level \d+", text) if match: print(f"Found: {match.group()}") else: print("No match")

Always check if the result is `None` before calling `.group()`, or you'll get an error!

Raw Strings

The `r` before the string (`r"\d+"`) means raw string — it tells Python not to interpret backslashes. Always use raw strings for regex patterns!

Exercise 3 — Basic Patterns

Here are the most common regex patterns:

Common Regex Patterns

`\d` — any digit (0-9) `\w` — any word character (letter, digit, underscore) `\s` — any whitespace (space, tab, newline) `.` — any character except newline `+` — one or more of the previous `*` — zero or more of the previous `?` — zero or one of the previous

Let's see `re.findall()` in action — it returns all matches as a list, not just the first one:

import re text = "Aquachu HP: 100, Level: 25" digits = re.findall(r"\d+", text) words = re.findall(r"\w+", text) print("Digits:", digits) print("Words:", words)

Exercise 4 — findall Result

What is printed?

import re text = "Aquachu: 100 HP, Pyrochu: 85 HP" result = re.findall(r"\d+", text) print(result)
Options
• ["100", "85"]
• [100, 85]
• ["100 HP", "85 HP"]
• ["Aquachu", "Pyrochu"]

Hint : `\d+` matches digits only. `findall()` returns matches as strings, not numbers.

Exercise 5 — Find All Digits

Complete the code to find all numbers in the text.

Hint : Which `re` function returns ALL matches as a list?

Exercise 6 — re.sub() — Replace Matches

`re.sub(pattern, replacement, text)` replaces all matches with a new string. It's like `str.replace()` but with the power of regex!

import re text = "Aquachu has 100 HP" result = re.sub(r"\d+", "???", text) print(result)

Every group of digits got replaced by `"???"`. This is great for censoring, formatting, or cleaning data.

Exercise 7 — Replace with Regex

Complete the code to replace all numbers with `"X"`.

Hint : Which `re` function replaces matches? The second argument is the replacement string.

Exercise 8 — Character Classes and Groups

You can define your own character sets with square brackets `[]`. And use parentheses `()` to capture groups.

import re text = "Aquachu-Water, Pyrochu-Fire" pairs = re.findall(r"(\w+)-(\w+)", text) print(pairs) for name, element in pairs: print(f"{name} is {element} type")

`(\w+)-(\w+)` captures two groups separated by a dash. `findall()` returns a list of tuples when you use groups!

Character Classes

`[abc]` matches a, b, or c `[A-Z]` matches any uppercase letter `[0-9]` is the same as `\d` `()` captures groups you can extract separately

Exercise 9 — Groups

What is printed?

import re text = "Aquachu:Water" match = re.search(r"(\w+):(\w+)", text) print(match.group(2))
Options
• "Aquachu:Water"
• "Aquachu"
• "Water"
• "(\w+):(\w+)"

Hint : `.group(1)` is the first capture group, `.group(2)` is the second. Which word comes after the colon?

Exercise 10 — Anchors: ^ and $

Anchors don't match characters — they match positions. `^` means "start of string" and `$` means "end of string".

import re names = ["Aquachu", "Florachu", "Zap"] for name in names: if re.search(r"^[AZ]", name): print(f"{name} starts with A or Z") else: print(f"{name} does NOT start with A or Z") if re.search(r"chu$", name): print(f"{name} ends with 'chu'") else: print(f"{name} does NOT end with 'chu'")

Exercise 11 — Anchor Pattern

Complete the regex to check if the name starts with `"Aqua"`.

Hint : Which anchor means "start of string"?

Exercise 12 — Regex Patterns

Match each regex pattern with its meaning:

Items to match
• \d+
• \w+
• \s
• .
• ^
• $
Definitions
• One or more digits
• One or more word characters
• A whitespace character
• Any character (except newline)
• Start of string
• End of string

Exercise 13 — Codémon Data Parser

Parse a Codémon database string using regex! Given: `"Aquachu(Water,Lv.15) Pyrochu(Fire,Lv.25) Florachu(Plant,Lv.10)"` 1. Use `re.findall()` with groups to extract: name, element, and level for each Codémon 2. Print each as: `"Aquachu - Water type, Level 15"` 3. Use `re.sub()` to replace all levels with `"Lv.99"` 4. Print the modified string

Starter code
import re data = "Aquachu(Water,Lv.15) Pyrochu(Fire,Lv.25) Florachu(Plant,Lv.10)" # 1 & 2: Extract and print each Codémon # 3 & 4: Replace all levels with Lv.99
Back to the course