Bug hunt

Anchors, Boundaries & Flags

Some pattern pieces match a position, not a character:

  • ^ start of the string, $ end of the string
  • \b a word boundary, the edge between a word character and a non-word character. r"\bcat\b" matches cat but not category.

Flags change how a pattern behaves:

  • re.IGNORECASE (re.I): letters match either case
  • re.MULTILINE (re.M): ^ and $ match at every line
  • re.VERBOSE (re.X): whitespace and # comments inside the pattern are ignored, so long patterns can be laid out nicely

Combine flags with |. If you use a pattern a lot, compile it once:

import re
WORD = re.compile(r"\boil\b", re.IGNORECASE)
WORD.findall("Oil? OIL! Boil...")   # ['Oil', 'OIL']

The bug

The harbor master's tools are broken:

  • count_word("Oil, oil, OIL! Boil the oil.", "oil") should be 4 (any case, but not inside Boil). It returns 0.
  • warnings(log) should return the message of every line that starts with WARN: . It returns [].

Assignment

Find and fix the two bugs. (re.escape(word) is fine: it makes any special characters in word literal.)