
Your First Pattern
A regular expression (regex) is a tiny language for describing the
shape of text: "an L followed by some digits" instead of one exact
string. Python's re module speaks it.
Write patterns as raw strings (r"...") so backslashes reach re
untouched. For now you need just two symbols: \d means any digit and
+ means one or more of the previous thing.
import re
log = "Relit L42, then L7."
m = re.search(r"L\d+", log) # first match anywhere
print(m.group()) # L42
print(re.findall(r"L\d+", log)) # ['L42', 'L7']
The four everyday functions:
| Function | Looks for a match... | Returns |
|---|---|---|
re.search(p, s) |
anywhere in s |
a Match or None |
re.match(p, s) |
only at the start of s |
a Match or None |
re.fullmatch(p, s) |
covering all of s |
a Match or None |
re.findall(p, s) |
everywhere | a list of strings |
A Match object is truthy, None is falsy, so if re.search(...):
reads naturally. Call .group() to get the matched text.
Pip tip: Use
fullmatchfor validating ("is this whole thing a code?") andsearch/findallfor finding codes inside longer text.
Assignment
A lantern code is a capital L followed by one or more digits (L7, L042).
first_code(text)returns the first lantern code intextas a string, orNoneif there isn't one.all_codes(text)returns a list of every code intext.is_code(text)returnsTrueif the whole oftextis a lantern code, otherwiseFalse(a realbool).
A lantern code is a capital L followed by one or more digits (L7, L042).
first_code(text)returns the first lantern code intextas a string, orNoneif there isn't one.all_codes(text)returns a list of every code intext.is_code(text)returnsTrueif the whole oftextis a lantern code, otherwiseFalse(a realbool).
Press Run to try your code, then Check to test it.