# How to Write a Regex with an AI Agent, Test Cases First

> Canonical: https://skillalmanac.com/learn/write-a-regex-with-an-ai-agent | Updated: 2026-11-21 | Index status: not offered to search engines

Write a regex from a spec by listing must-match and must-not-match strings first, then testing the pattern. Steps and pitfalls.

## Facts

- 2026-11-21: re.fullmatch requires the entire string to match, while re.search returns the first match found anywhere in the string (https://docs.python.org/3/library/re.html)
- 2026-11-21: By default in Python, $ matches at the end of the string or just before a newline at the end of the string (https://docs.python.org/3/library/re.html)
- 2026-11-21: In Python str patterns, \d matches any Unicode decimal digit, and the re.ASCII flag limits it to 0-9 (https://docs.python.org/3/library/re.html)
- 2026-11-21: Quantifiers with a trailing ? are lazy; the pattern <.*?> matches '<a>' in '<a> b <c>' (https://docs.python.org/3/library/re.html)
- 2026-11-21: MDN says a regex literal is compiled when the script loads, while new RegExp(string) compiles at runtime, which suits patterns built from input (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions)
- 2026-11-21: In JavaScript with the g flag, exec() and lastIndex track where the next search starts, so reusing one regex object changes later results (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions)

Write the test table before the pattern: list strings that must match and strings that must not match, then write the regex and run it against every row. This order gives an agent a fixed target, so each failing row points to one specific mistake instead of a general sense that the pattern is off.

## Steps

1. Write the spec in one sentence that names the exact input shape, for example "a four-digit year with no sign and no spaces."
2. Build the table before asking for a pattern. Include at least five must-match rows and five must-not-match rows. Put the edge cases in the table: an empty string, a string with a trailing newline, a number with extra digits on either side, and digits from non-Latin scripts.
3. Give the agent the table and ask for a pattern that satisfies every row. Keep the table in a file so the agent can rerun it after each change.
4. Run the table in Python. Use `fullmatch` for whole-string rules:

```python
import re

pattern = re.compile(r"\d{4}")
must_match = ["1999", "2026"]
must_not_match = ["999", "20260", "12a4", "1999\n"]

for s in must_match:
    if not pattern.fullmatch(s):
        print("MISS (should match):", repr(s))
for s in must_not_match:
    if pattern.fullmatch(s):
        print("HIT (should not match):", repr(s))
```

5. Read the output. No lines printed means every row behaved as the table says. Then add one row you know should fail and confirm the script reports it, so you know the check can fail at all.

## Pitfalls

- **`search` instead of `fullmatch`.** `re.search(r"\d{4}", "x1999y")` returns a match, so a must-not-match row passes when it should fail. Notice it by adding rows with extra characters on either side. Fix it with `fullmatch` for whole-string rules.
- **`$` and the trailing newline.** In Python, `foo$` matches `"foo\n"` by default. Add a `"foo\n"` row to the table. Use `fullmatch`, or test the newline case explicitly.
- **Unicode digits.** In a Python `str` pattern, `\d` also matches digits such as Arabic-Indic ones. A row with such digits in the must-not-match list exposes this. Use `re.ASCII` when only 0-9 should count.
- **Greedy versus lazy.** `<.*>` on `"<a> b <c>"` matches the whole string, while `<.*?>` matches `"<a>"`. Add a row with two tags in one string to catch this.
- **Shared regex objects in JavaScript.** With the `g` flag, `exec()` and `lastIndex` carry state between calls. If the table loop reuses one object, results alternate between runs. Create the regex fresh for each test, or reset `lastIndex` to 0.

## When to use a skill instead

Writing the table first is a fixed procedure, and it is easy to skip when a prompt is one request among many. The [regex-case-tester](/skills/skill-almanac/regex-case-tester) skill takes a spec, builds the must-match and must-not-match table before it writes any pattern, runs that table with Python `re`, and reports the failing rows. It also flags patterns that risk catastrophic backtracking, which the table alone does not catch. Use the skill when you need the same check on many specs, and do the steps above by hand when you are testing one short pattern.

## FAQ

### How does a regex work?

A regex is a pattern that a matching engine compares against text. Python's `re.search` returns the first place the pattern matches, while `re.fullmatch` requires the whole string to fit the pattern.

### What regex pattern can I use to match a 4-digit number?

Use `\d{4}` to find four digits inside a string, and call `fullmatch` with the same pattern to accept only strings that are exactly four digits. In Python, add `re.ASCII` if non-ASCII digits should not count.

### What will the '$' regular expression match?

In Python, `$` matches at the end of the string or just before a single newline at the end, so `foo$` matches `"foo\n"`. In JavaScript without the `m` flag, `$` matches only at the end of the input.

## Related skills

- [regex-case-tester](https://skillalmanac.com/skills/skill-almanac/regex-case-tester.md): Platform Score 58/100 (provisional)

## Related guides

- [How to Use an AI Agent on a First Task You Can Check](https://skillalmanac.com/learn/how-to-use-an-ai-agent.md)
- [No-code AI agent builders: what to check first](https://skillalmanac.com/learn/no-code-ai-agent-builders-what-to-check.md)
- [How to Use AI to Write a Letter: Facts First, Then Tone](https://skillalmanac.com/learn/how-to-use-ai-to-write-a-letter.md)
- [Remotion Agent Skills: Install and Make a First Video](https://skillalmanac.com/learn/remotion-agent-skills-guide.md)
- [How to Write a PowerShell Script with Safe Dry Runs](https://skillalmanac.com/learn/write-a-powershell-script-with-an-ai-agent.md)
- [How to write a bug report a developer can reproduce](https://skillalmanac.com/learn/write-a-bug-report-with-ai.md)

## Sources

- https://docs.python.org/3/library/re.html
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions

Platform Scores report our assessment under a published method. They are not a safety guarantee.
