04 / FILES AND FORMATS · LESSON 16

Find structure in text

Parse a complete log line and reject malformed input.

14 min · learn at your pace

Start with ordinary string tools

strip, split, startswith, and membership tests solve many text problems. Reach for a regular expression when the shape of the text is the useful part: a fixed label, a changing hostname, and a small set of allowed states.

Python’s re module provides search for a match anywhere and fullmatch for the whole string. Using search to validate a complete record can accidentally accept a valid fragment inside otherwise invalid text. This exercise needs fullmatch.

Describe the shape carefully

A character class such as [A-Za-z0-9-]+ accepts one or more letters, digits, or hyphens. Parentheses capture a part for later use. (UP|DOWN) accepts either literal state. Raw strings, written with an r prefix, make patterns containing backslashes easier to read.

A failed match returns None. Check that before reading its groups. Regular expressions identify a text shape; they do not prove that a hostname exists or that a reported state is true. Our parser reports only what a supplied line says, and it never queries a device.

Try an example.py
import re
match = re.fullmatch(r"host=([A-Za-z0-9-]+) state=(UP|DOWN)", "host=web-01 state=UP")
if match:
    print(match.group(1), match.group(2))
YOUR TURN

Put it into practice.

Define parse_event(line). After stripping outer whitespace, accept exactly "host={name} state={UP or DOWN}" with one space between fields. Names contain only ASCII letters, digits, and hyphens, with at least one character. Return {"host": name, "state": state}, or None for invalid lines.

See an explained solution
One way to solve it.py
import re
def parse_event(line):
    match = re.fullmatch(r"host=([A-Za-z0-9-]+) state=(UP|DOWN)", line.strip())
    if match is None:
        return None
    return {"host": match.group(1), "state": match.group(2)}

The pattern checks the whole cleaned line and restricts both fields. Returning a dictionary lets later code work with fields instead of parsing the same text again.