By Priya Raman, NBT
Regular expressions are where an AI coding assistant looks most impressive and is most dangerous. Ask for "a regex that matches our log lines" and you get a dense one-liner in two seconds. It looks right. It passes the one example you had in mind. Three weeks later it silently skips every line where the component name has a hyphen in it.
The problem isn't that the assistant is bad at regex. It's that a regex is a tiny program with no names, no comments and no tests, and nobody reads it. This article is a routine that fixes all three. The examples are Python, and the regex details come from the Python 3.15 re module documentation, read on 6 December 2026. The routine works the same in JavaScript, Go or anything else.
If you want the general version of this skill, see our guide to prompting an AI coding assistant.
Step 1: give examples, not a description
"Match our log lines" is a description. The assistant has to guess what your log lines look like, and it'll guess the common case. Give it real lines instead, including the awkward ones, and say which should not match:
Write a Python regex to parse these log lines into timestamp, level, component and message.
Must match:
2026-12-06T17:10:02Z WARN [payments] retry 3/5 for order ORD-48213
2026-12-06T17:10:03Z ERROR [auth-service] token expired
2026-12-06T17:10:04Z INFO [db_pool](empty message)Must NOT match:
2026-12-06 17:10:02 WARN [payments] retry(space instead of T, no Z)
WARN [payments] retry(no timestamp)
2026-12-06T17:10:02Z TRACE [payments] x(TRACE is not a level we use)
The negative examples matter more than the positive ones. They're where the edges of the pattern get decided, and they're exactly what a description leaves out.
Step 2: ask for a pattern a person can read
Python has a flag for this. The docs describe re.VERBOSE (also re.X) as letting you "visually separate logical sections of the pattern and add comments". Whitespace in the pattern is ignored, except inside a character class or after a backslash, and # starts a comment.
Ask for it explicitly:
Use re.VERBOSE with one comment per part, and named groups.
You get something like this:
import re
LOG_LINE = re.compile(r"""
(?P<ts>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z) # UTC timestamp, ISO 8601
\s+
(?P<level>DEBUG|INFO|WARN|ERROR) # only the levels we use
\s+
\[(?P<component>[a-z0-9_-]+)\] # [component], may have - or _
\s?
(?P<message>.*) # the rest, may be empty
""", re.VERBOSE)
Now a reviewer can check each line against the examples. "Component allows hyphens and underscores" is visible, not buried in [a-z0-9_-]+ in the middle of a one-liner.
Step 3: match the whole string on purpose
The most common regex bug isn't in the pattern; it's in the function that runs it. re.search finds a match anywhere. re.match anchors only at the start. re.fullmatch requires the whole string to match.
For validation (an order ID, a postcode, a username), you almost always want fullmatch. Otherwise ORD-48213; DROP TABLE passes because it starts with a valid ID.
Make it part of the prompt:
Use fullmatch for validation. Tell me which function you chose for parsing and why.
Step 4: turn the examples into tests
You already wrote the test cases in step 1. Ask the assistant to make them executable:
Turn every example above into a pytest test. Positive examples should check each named group's value. Negative examples should assert no match.
import pytest
from logparse import LOG_LINE
@pytest.mark.parametrize("line, level, component, message", [
("2026-12-06T17:10:02Z WARN [payments] retry 3/5 for order ORD-48213",
"WARN", "payments", "retry 3/5 for order ORD-48213"),
("2026-12-06T17:10:03Z ERROR [auth-service] token expired",
"ERROR", "auth-service", "token expired"),
("2026-12-06T17:10:04Z INFO [db_pool] ", "INFO", "db_pool", ""),
])
def test_matches(line, level, component, message):
m = LOG_LINE.fullmatch(line)
assert m
assert (m["level"], m["component"], m["message"]) == (level, component, message)
@pytest.mark.parametrize("line", [
"2026-12-06 17:10:02 WARN [payments] retry",
"WARN [payments] retry",
"2026-12-06T17:10:02Z TRACE [payments] x",
])
def test_rejects(line):
assert LOG_LINE.fullmatch(line) is None
Then the rule for the rest of the project: every time the regex changes, a new example comes with it. When production shows a line that broke parsing, the first commit is a failing test with that line. The fix comes second.
Step 5: make the assistant break its own pattern
Once tests pass, switch roles:
Find three realistic lines that this pattern gets wrong: either matches when it shouldn't, or doesn't match when it should. Add each as a test, then fix the pattern.
This is where assistants shine. They're good at imagining inputs: uppercase components, tabs instead of spaces, a trailing \r from a Windows log, a timestamp with milliseconds. Some of these you'll decide are fine to reject. That decision, written as a test, is now documentation.
Step 6: check it can't hang
Some patterns take exponentially long on certain inputs, because the engine tries every way to split the text between nested repeats. The classic shape is a repeat inside a repeat, like (a+)+, run against a long string that almost matches.
Ask:
Does this pattern have nested quantifiers that could backtrack badly? Add a test that runs it on a 10,000-character line that almost matches and fails if it takes more than 100 ms.
Python 3.11 added two tools for this, per the re docs: possessive quantifiers (*+, ++, ?+) and atomic groups ((?>...)). Both stop the engine from going back into the part they cover. The docs describe x*+ as equivalent to (?>x*). If the assistant suggests one, ask it to explain what it prevents, and keep the timing test either way.
Step 7: ask for an explanation you can check
Last prompt:
Explain this pattern part by part in plain English, and for each part say which test covers it.
If a part has no test, you've found a gap. If the explanation doesn't match what the tests show, one of them is wrong, and the tests win.
The checklist
- Real examples, including must-not-match lines.
-
re.VERBOSE, comments, named groups. -
fullmatchfor validation. - Examples become tests; every change brings a new example.
- The assistant attacks its own pattern.
- A timing test on a long near-miss.
- An explanation mapped to tests.
That's maybe ten extra minutes. In return you get a regex that someone, including you next year, can actually read and safely change.
Top comments (1)
Step 5 is the one most teams skip, and it's the one that would have caught the hyphen bug from your intro — the assistant imagining inputs is exactly what a tired reviewer won't do. One gap I'd add: the log lines in step 1 are all well-formed except for the deliberate rejects, but production logs are rarely that clean. Your step-5 prompt covers uppercase components and tabs, but I'd make one of the three adversarial lines a truncated line, cut off mid-message. That's the failure mode that silently drops data instead of loudly failing, and it's the one your must-not-match list doesn't cover yet.
Two concrete additions. First, pin the 100 ms budget from step 6 into CI rather than leaving it as a local test — a 10,000-character near-miss that passes on a developer laptop can still blow the budget on a cold container. Second, the fullmatch rule in step 3 deserves the same treatment for the timestamp group: the pattern accepts 2026-12-06T17:10:02Z, but it would also accept 2026-13-45T99:99:99Z, because it's checking shape, not time. Would you add a range check on the timestamp groups, or keep the regex to shape and let the parser reject impossible dates?