Code

Capture Groups

Parentheses capture part of a match so you can pull it out.

import re

m = re.search(r"(\d+) x (\w+)", "order: 3 x oil")
m.group(0)   # '3 x oil'  (the whole match)
m.group(1)   # '3'
m.groups()   # ('3', 'oil')

Named groups (?P<name>...) make patterns self-documenting:

m = re.fullmatch(r"(?P<isle>\w+):(?P<n>\d+)", "Ember:12")
m["isle"]        # 'Ember'
m.groupdict()    # {'isle': 'Ember', 'n': '12'}

Two more things worth knowing:

  • With groups, re.findall returns the groups, not the whole match. Two groups give a list of tuples: [('3', '4'), ...].
  • (?:...) groups without capturing, e.g. (?:ab)+ for "ab repeated".

Parentheses are special, so to match a literal ( write \(.

Assignment

  1. parse_order(line) handles lines like "order 17: 3 x Healing Potion". If the whole line fits that shape, return {"id": 17, "qty": 3, "item": "Healing Potion"} (with int values); otherwise return None. The item is everything after "x ".
  2. coordinates(text) finds every pair like (3, -4) (numbers may be negative, the space after the comma is optional) and returns a list of integer tuples, e.g. [(3, -4), (10, 2)].