Loading WURK...
RomanMotion
RomanMotion
Product ad & launch videos · 3D product visuals · app & AI builder. Concept to final cut in days. Open for projects.

Let your coding agent write the regex, then test it on real examples

Give your coding agent real match and no-match examples, keep them as tests, and check the regex for slow backtracking before you ship.

Published on November 9, 20266 min read

Your coding agent wrote the regex, your one example passed, and you're about to ship it. A pattern that looks right can reject valid users or make your server work far too hard on a crafted input. This routine turns your real examples into tests and adds a safety check before the pattern reaches production.

Start with examples and the rules they represent, then tell your agent which language and regex engine your app uses. Ask for an explanation, keep the examples as automated tests, and review the pattern for excessive backtracking. For complex formats, consider a dedicated parser instead.

Start with examples, not a pattern

A regex is useful when the accepted shape is simple and you can state the rules. A project slug, for example, might allow lowercase letters and digits separated by single hyphens. That does not mean the same restrictions belong on a person's name.

A pattern tested only against my-project tells you little about project-2, -project, or an empty string. The useful question is not "Does this example match?" but "Does the pattern accept and reject the cases my product actually supports?"

Collect 8 to 10 strings that must match and 8 to 10 that must not. Use representative examples from your data, with permission, or create sanitized equivalents. Include boundaries, punctuation, whitespace, different letter cases, and near-misses. Don't paste customer details or secrets into the prompt.

Write down decisions that examples alone might leave unclear: should uppercase letters be accepted, normalized, or rejected? Is a trailing newline allowed? If you don't know, decide the product rule before asking the agent to encode it.

Give the agent a testable brief

Name the runtime and engine, not just "JavaScript" or "Python" if your setup uses a separate regex library. Syntax, flags, character classes, and matching behavior can differ between engines (OWASP input validation guidance).

Copy and fill in this prompt:

Write a regex for [field and purpose].

Language, runtime, and regex engine: [details]
The entire input must match: [yes/no]
Allowed characters and format: [rules]
Length limit, applied before matching: [limit]
Normalization before matching: [none or exact rules]

Must match:
[paste 8 to 10 representative strings]

Must not match:
[paste 8 to 10 representative strings]

Explain every part of the pattern and each flag in plain language.
Show how the pattern is called in this engine. Use whole-input
matching if required. Turn the examples into automated tests.
Identify ambiguous rules, near-miss cases, and possible
backtracking risks. Do not change the acceptance rules silently.

This works best when the agent can run the tests itself and show you the output, instead of pasting a pattern into chat; if you don't have that set up, you can try the zcode agent harness free.

Review the explanation against your rules. If the agent says a piece is needed but can't explain which case it handles, ask for a concrete example. If it proposes restricting valid characters to make the regex easier, that's a product decision, not an automatic improvement.

Check the match boundary and keep the tests

For validation, you often want the whole value to match, not a valid-looking fragment inside it. Anchors such as ^ and $ can express boundaries, but their behavior depends on the engine and flags. In JavaScript, the m flag also lets those assertions match at line boundaries (MDN).

In Python, re.fullmatch() checks the whole string directly (Python documentation). The example below uses it for an illustrative slug rule, not email addresses or names. Its maximum length is an example product decision.

# slug.py
import re

SLUG = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
MAX_LENGTH = 20

def valid_slug(value):
    if not isinstance(value, str) or len(value) > MAX_LENGTH:
        return False
    return SLUG.fullmatch(value) is not None

Keep this test file beside that code. It imports the production function, so the tests exercise the actual validator rather than a separate copy of the pattern.

# test_slug.py
import unittest
from slug import valid_slug

class SlugTests(unittest.TestCase):
    def test_examples(self):
        cases = [
            ("a", True),
            ("home", True),
            ("task-42", True),
            ("a-b", True),
            ("9-lives", True),
            ("123", True),
            ("z", True),
            ("a" * 20, True),
            ("", False),
            ("-task", False),
            ("task-", False),
            ("task--one", False),
            ("My-Task", False),
            ("two words", False),
            ("task\n", False),
            ("a" * 21, False),
        ]
        for value, expected in cases:
            with self.subTest(value=value):
                self.assertEqual(valid_slug(value), expected)

if __name__ == "__main__":
    unittest.main()

Run it with python test_slug.py. Replace the illustrative cases with your agreed rules and representative data, then run the tests whenever the validator changes. A passing table shows those cases worked; it doesn't prove every possible input is safe.

Check for catastrophic backtracking

Some regex engines try alternative ways to match when a path fails. With certain patterns, a long input that almost matches can trigger an excessive number of attempts. An attacker may use that behavior for regular expression denial of service, or ReDoS (OWASP ReDoS).

OWASP identifies repeated groups containing another repetition or overlapping alternatives as warning signs. Its examples include (a+)+$ and (a|aa)+$. Don't assume every nested repetition is unsafe, but treat ambiguous repetition as a reason to inspect the pattern and engine.

Cap input length before matching. Pick the cap from the field's actual requirements and enforce it on the server, even if the interface also has a limit. A cap reduces exposure; it does not prove an expensive pattern is safe. OWASP also recommends considering a non-backtracking engine or a match timeout where supported (OWASP input validation cheat sheet).

Ask the agent for long, near-matching inputs and a simpler pattern. Run performance checks in an isolated test process with an enforced timeout, not against production. Treat a timeout as a failure, investigate it, and remember that a few fast test runs cannot prove the absence of ReDoS.

Know when to use a parser instead

For URLs, use a URL parser and then check your application's rules. In JavaScript, new URL(value) parses an absolute URL and throws if it cannot parse it; a relative reference needs a base (MDN URL constructor). Parsing alone doesn't establish that a destination is trustworthy or safe for your server to fetch.

For email addresses, use a maintained validation library suited to your mail system. A format check cannot prove someone controls the mailbox; verify ownership separately (OWASP email validation guidance).

For HTML, use a parser for structure and an appropriate sanitizer before accepting untrusted HTML for display. Parsing and sanitizing are different jobs (OWASP rich-content guidance).

For dates, use a date parser and check the business rule as well: a date can be valid yet outside the range your app accepts. Python's datetime documentation covers parsing and invalid values (Python documentation).

The checklist

  • 8 to 10 real must-match and must-not-match strings, near-misses included
  • The engine named in the prompt, and every part of the pattern explained
  • Whole-input matching (fullmatch or anchors that fit your engine)
  • The examples kept as a test file that runs whenever the validator changes
  • A length cap before matching, and no ambiguous nested repetition
  • A parser instead of a regex for URLs, emails, HTML and dates

The agent can write the pattern, but your examples and acceptance rules define whether it does the right job. If you're picking a plan for an agent that writes and tests small pieces like this all day, there's 10% off GLM coding plans. For more on checking what your agent hands you, see Review an AI-written diff in 10 minutes, and there's more on our blog about working with coding agents.

If this kept a bad regex out of production, a small tip on the post keeps these guides coming.

Conversation

Join the conversation

Share your thoughts with the author and other readers.

Comments0

Checking your account…

Latest comments

0
No comments yet. Be the first to share your thoughts.