Code

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 fullmatch for validating ("is this whole thing a code?") and search/findall for finding codes inside longer text.

Assignment

A lantern code is a capital L followed by one or more digits (L7, L042).

  1. first_code(text) returns the first lantern code in text as a string, or None if there isn't one.
  2. all_codes(text) returns a list of every code in text.
  3. is_code(text) returns True if the whole of text is a lantern code, otherwise False (a real bool).