← Tous les articles

Getting regexes from an AI assistant: test them before you trust them

Coding assistants produce regular expressions in seconds and with total confidence. They often work on the example you gave and let everything else through. Our approach: positive and negative examples, a runnable test table, and an eye on PHP versus JavaScript differences.

Getting regexes from an AI assistant: test them before you trust them

Key points

  • Give the assistant inputs that must match and inputs that must not.
  • Turn those examples into a runnable test table before the pattern ships.
  • Name the language: PHP (PCRE) and JavaScript don’t always read a pattern the same way.

Regular expressions might be the task developers hand over to coding assistants most eagerly. Nobody enjoys writing them, and the answer comes back in seconds, neatly explained. The catch is that a regex that “works” on your one example says nothing about the inputs you didn’t mention. On our projects, bugs traced back to generated regexes almost always share that root cause: the pattern looked right and nobody really exercised it.

Ask with counter-examples

“Regex for an order reference” gets you a pattern that accepts the reference and plenty of other things. What actually changes the output is describing both sides: CMD-2026-000123 must match; XCMD-2026-000123, CMD-2026-0001234 and cmd-2026-000123 must not; several references can appear in one text.

Say where the pattern will run (PHP’s preg_match, JavaScript, a database) and ask for a piece-by-piece explanation. When the explanation of one part is vague, that part is often useless or wrong.

Turn the examples into tests

The examples from your prompt become a test table you can run. It takes a few lines and stays in the codebase for the day someone wants to “simplify” the pattern:

const ORDER_REF = /bCMD-(d{4})-(d{6})b/g;

const cases = [
  ['Order CMD-2026-000123 received', ['CMD-2026-000123']],
  ['CMD-2026-000123, CMD-2025-000045', ['CMD-2026-000123', 'CMD-2025-000045']],
  ['XCMD-2026-000123', []],            // glued to another word
  ['CMD-2026-0001234', []],            // one digit too many
  ['cmd-2026-000123', []],             // lowercase rejected
  ['', []],
];

for (const [input, expected] of cases) {
  const got = [...input.matchAll(ORDER_REF)].map((m) => m[0]);
  console.assert(
    JSON.stringify(got) === JSON.stringify(expected),
    `${JSON.stringify(input)} -> ${JSON.stringify(got)}`
  );
}

Always add edge cases: empty string, leading or trailing spaces, accented characters, line breaks. That’s where most generated patterns we’ve reviewed fell over.

Language-specific traps

Assistants happily blend syntaxes from different engines. The one we hit most in PHP is the end anchor:

// In PHP, $ also matches before a final newline: "12345n" passes.
preg_match('/^d{5}$/', "12345n");   // 1
// z (or the D modifier) really anchors at the end.
preg_match('/^d{5}z/', "12345n");  // 0

$result = preg_match($pattern, $input);
if ($result === false) {
    // backtrack limit hit, invalid pattern...
    error_log('Regex error: ' . preg_last_error_msg());
}

In form validation, that accepted newline can end up in your database. Also watch for nested quantifiers such as (a+)+, which can blow up on certain inputs. In JavaScript the page freezes; PHP stops at its backtrack limit and preg_match returns false, which a plain if (!preg_match(...)) treats as “no match”.

Is a regex the right tool at all?

Ask the assistant that question too. For email addresses, PHP’s filter_var($email, FILTER_VALIDATE_EMAIL) or an <input type="email"> beats a home-made pattern. For URLs, use parse_url() or JavaScript’s URL. For HTML, a real parser. Regexes shine on simple, well-defined internal formats like an order reference.

FAQ

Can the assistant write the tests too?

Yes, and it’s handy for spotting cases you missed. Review every expected result, though: if the assistant misunderstood the format, it can make the same mistake in the tests.

Isn’t an online regex tester enough?

It’s great for exploring, provided you pick the right engine (PCRE or JavaScript). For the long run, tests belong in the project, not in a browser tab.

Is your team using coding assistants and wants to keep quality under control? We help set up tests and review habits that fit your projects.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →