Course outline · 0% complete

0/27 lessons0%

Course overview →

re basics: patterns, classes, quantifiers

lesson 7-1 · ~14 min · 18/27

Quiz

Warm-up from Python for Beginners: which expression checks whether the substring "cat" appears anywhere in text?

Patterns, not substrings

Working engineers meet pattern-shaped problems weekly: validate a product code, pull the order numbers out of ten thousand log lines, find every price in a receipt. String methods can only test exact substrings, so Python ships a small pattern language for describing text by shape instead.

A regular expression (regex) describes a shape of text. Python's re module matches those shapes:

import re

m = re.search(r"\d\d\d", "order 472 shipped")
m.group()   # '472'

The building blocks:

PieceMatches
catthe literal letters c, a, t
\done digit, \w a letter/digit/_, \s whitespace
.any single character
[aeiou]one character from the set
[^0-9]one character NOT in the set

Always write patterns as raw strings r"..." so backslashes reach the regex engine untouched. re.search finds the first match anywhere and returns a match object, or None if nothing matched, so if m: is the standard guard.

Quantifiers and anchors

Repetition comes from quantifiers, which apply to the piece right before them:

QuantifierMeaning
+one or more
*zero or more
?zero or one
{3}exactly 3
{2,4}between 2 and 4

So \d+ is a whole run of digits and [a-z]{3} is exactly three lowercase letters. Anchors pin the pattern in place: ^ means start of string, $ means end. ^\d{4}$ matches a string that is entirely four digits, nothing before or after.

pattern: r"\d+"order472!re.search slides left to right and stops at the first place the pattern fits
re.search scans the string from the left and returns the first stretch that fits the pattern.

Code exercise · python

Run this program. Note the if m: guard, and how the anchored pattern rejects the string with extra text around the digits.

Code exercise · python

Your turn. Write a pattern that matches a product code: exactly 2 uppercase letters followed by exactly 3 digits, and nothing else in the string. Test it on the three candidates.

Code exercise · python

Your turn, one more. Build a pattern matching a 24-hour clock time like "09:30": exactly two digits, a colon, exactly two digits, and nothing else in the string. The loop prints each candidate's verdict.

Quiz

What does the pattern r"ab?c" match?