Library › Coding AI › Software developers

Write a Python log regex with exact group names

Practice: Setting limits and rules. About 5 minutes.

About this exercise

Your alerting script needs a compiled regex that matches only WARN and ERROR lines (INFO must not match). Use Python named groups exactly ts, level, worker and msg, anchor it with ^ and $, and write it as one line: LOG_RE = re.compile(r"...") with no flags. Exactly 1 code block with that single line, under 30 words of text.

Common mistakes when you ask AI for this

  • Matching every level. A generic log regex matches INFO and DEBUG too, so the alert fires constantly. Try: Add: "Only WARN or ERROR may match."
  • Wrong group names. scan() reads ts, level, worker and msg by name; the AI picks timestamp or message. Try: Add: "Named groups exactly ts, level, worker, msg."
  • A verbose multi-line pattern. The AI likes re.VERBOSE with comments across many lines. Try: Add: "One line: LOG_RE = re.compile(r\"...\"), no flags."
  • A tutorial and test code. The AI explains each part and adds a test loop. Try: Add: "One code block with the one line, one short sentence max."

What a strong prompt includes

  • Limits the levels
  • Names the groups
  • Asks for one line
  • Rules out flags
  • Asks for anchoring

Practice this now ↑

Related exercises