chatbot1-6 Exercise 3: What Redaction Misses, and Over-Catches ================================================================= ex3.py (save in the project root): import re from bot.privacy import redact POSTCODE = re.compile(r"\b[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}\b") # UK postcode shape, e.g. EH1 1YZ def redact_more(text: str) -> str: return POSTCODE.sub("[postcode]", redact(text)) for t in ["I'm at EH1 1YZ, call 0131 496 0000", "My name is Ada Lovelace and I live at 14 Rose Street", "Order 12345 is late", "Meet at room B12 3AB tomorrow"]: print(f"{t!r:58} redact: {redact(t)!r:50} redact_more: {redact_more(t)!r}") Run with: py ex3.py Output: "I'm at EH1 1YZ, call 0131 496 0000" redact: "I'm at EH1 1YZ, call [number]" redact_more: "I'm at [postcode], call [number]" 'My name is Ada Lovelace and I live at 14 Rose Street' redact: 'My name is Ada Lovelace and I live at 14 Rose Street' redact_more: 'My name is Ada Lovelace and I live at 14 Rose Street' 'Order 12345 is late' redact: 'Order 12345 is late' redact_more: 'Order 12345 is late' 'Meet at room B12 3AB tomorrow' redact: 'Meet at room B12 3AB tomorrow' redact_more: 'Meet at room [postcode] tomorrow' What this tells you about regular-expression redaction: 1. Names and street addresses (the second line) are untouched. A pattern can match the shape of a phone number or an email, but a name or an address has no fixed shape. Catching them needs a different technique (a named-entity model, or simply not logging the text), and neither is perfect. 2. A postcode-shaped pattern also matched "B12 3AB" in "room B12 3AB", which is not a postcode (the fourth line). Over-matching is the other failure: here it hid harmless text, which is the safe direction for a log filter, but in other uses a false match can destroy useful data. 3. So treat redaction as a safety net, not a guarantee. The reliable control is to log less: record flags and ids, not messages. WHY THIS WORKS AS AN ANSWER --------------------------- redact() applies three patterns in order: email, long digit runs (card-shaped) and phone-shaped numbers. redact_more() adds a UK postcode pattern on top. The output shows each rule doing its job on the first sentence, and the limits on the others: the name and address pass through, a five-digit order number is correctly left alone, and the lookalike room code is wrongly hidden. The postcode regex is a simplified shape (letters, a digit, an optional letter or digit, an optional space, a digit and two letters), not a validator.