
Code
Classes & Quantifiers
Patterns are built from what to match and how many.
What: character classes
| Pattern | Matches |
|---|---|
\d |
a digit 0-9 |
\w |
a "word" character: letter, digit or _ |
\s |
whitespace (space, tab, newline) |
. |
any character except newline |
[aeiou] |
one of these characters |
[A-Z] |
one character in the range |
[^0-9] |
anything except these |
Capitals flip the meaning: \D is a non-digit, \S non-whitespace.
To match a real dot, escape it: \.
How many: quantifiers
| Quantifier | Means |
|---|---|
? |
0 or 1 (optional) |
* |
0 or more |
+ |
1 or more |
{3} |
exactly 3 |
{2,4} |
2 to 4 |
A quantifier applies to the single thing right before it.
import re
re.fullmatch(r"[A-Z]{2}\d{3}", "QX101") # Match
re.fullmatch(r"colou?r", "color") # Match: u is optional
re.findall(r"\d+\.\d", "1.5 and 22.75") # ['1.5', '22.7']
Assignment
is_ship_id(s)returnsTrueonly if all ofsis a valid ship ID: 2 or 3 uppercase letters, a dash, 3 or 4 digits, then an optional single lowercase letter. Valid:AB-123,XYZ-2048,QR-555b.find_prices(text)returns a list of every price intext. A price is one or more digits, a dot, then exactly two digits (4.50,12.00).
is_ship_id(s)returnsTrueonly if all ofsis a valid ship ID: 2 or 3 uppercase letters, a dash, 3 or 4 digits, then an optional single lowercase letter. Valid:AB-123,XYZ-2048,QR-555b.find_prices(text)returns a list of every price intext. A price is one or more digits, a dot, then exactly two digits (4.50,12.00).
main.py Python sleeping
Press Run to try your code, then Check to test it.