Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Strings & text processingMiddleCommonPractical

Parse log lines like `2026-08-22 ERROR timeout` into timestamp, level and message fields, rejecting malformed lines.

Answer

Compile one anchored regular expression with named capture groups, then use `fullmatch` so partial garbage cannot be silently accepted. Return the named groups for valid lines and a clear sentinel such as `None` for malformed input. Compiling once is especially useful when the same pattern processes many lines.

Strong answer includes

  • uses an anchored/full-match regex
  • uses named capture groups
  • handles malformed input explicitly

Practical example

Strict log parser with named groups
import re

LOG_LINE = re.compile(
    r"(?P<date>\d{4}-\d{2}-\d{2}) (?P<level>INFO|WARNING|ERROR) (?P<message>.+)"
)

def parse_log(line):
    match = LOG_LINE.fullmatch(line)
    return match.groupdict() if match else None

print(parse_log("2026-08-22 ERROR timeout waiting for API"))
print(parse_log("ERROR timeout"))

fullmatch requires the entire line to satisfy the format; groupdict() returns a readable mapping from the named groups.

Expected result: A dict with date/level/message for the first line, then None.

#regex#strings#parsing

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules