Lesson 01
Regular Expressions — Search Patterns with the re Module
Learn what a Python regular expression is, why the re module exists, and the path from search functions to classes and quantifiers.
A regular expression is a search pattern. You write the shape of the text you want, and Python's re module finds it.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- Why regular expressions exist
- The definition of a pattern
- Where patterns show up in real software
- The order of the lessons in this module
The picture
The purpose is data validation: check that text has the shape you expect before the rest of the program trusts it. A pattern is language-independent. Python implements it with the re module.
A pattern is a mix of letters, digits, and symbols. That mix is the search rule. The rule runs against a string and returns the pieces that fit.
| Place patterns are used | What they do there |
|---|---|
| Compilers and interpreters | Recognize the tokens of a language |
| Operating-system tools | Filter names and paths |
| Network protocols | Recognize commands and addresses |
| Pattern matching | Pull the useful part out of a larger string |
You do not need to build a compiler to use this. The same idea checks a code, a word, or a decimal in an ordinary Python string.
Patterns are written as strings. Prefer a raw string, r"\d+", so Python does not treat the backslash as its own escape before re sees it.
This module stays on the re tools from the notes: findall, search, finditer, group, start, end, and sub, then character classes and quantifiers.
Example
import re
text = "Avery Lane scored 18"
print(re.findall(r"\d+", text))\d+ means one or more digits. The playground prints ['18']. The later lessons explain each symbol. For now, notice that the pattern is a string and the data is a separate string.
Key takeaways
-
A regular expression is a search pattern
-
Python patterns live in the
remodule -
Raw strings keep backslashes for the pattern
-
The path is functions, then character classes, then quantifiers, then a combined check
-
Next: re Functions — find every match, the first match, and a replacement
-
Previous: Polymorphism
Loading playground…
Check your understanding
Regular expressions overview quiz
A regular expression is:
1 / 10