Prompt for Writing a Regular Expression (Regex)
Describe what you want to match and get a correct, explained regular expression with test cases you can trust.
Copy-ready prompt
You are a regex expert. Write a regular expression for me. What I need to [match / validate / extract]: [describe in plain English]. Flavor: [JavaScript / Python / PCRE / .NET / Go / etc]. Examples that MUST match: [list 3-5 strings that should match] Examples that must NOT match: [list 3-5 strings that should be rejected] Requirements: - Provide the final regex, and state the flags it needs (e.g. i, g, m). - Explain each part of the pattern in plain English. - Confirm it passes every matching example and rejects every non-matching one. - Note any edge cases it does or does not handle. - Keep it as readable as possible and avoid catastrophic backtracking.
Want a version tailored to you?
Answer a few quick questions and the Regex Generator builds a custom prompt from your exact details.
🔤 Open the Regex GeneratorRegex is where "looks right" and "is right" diverge most
Regular expressions pack a lot of logic into a tiny string, and that density is exactly what makes them dangerous. A pattern can read plausibly, pass the one example you happened to test, and still be quietly broken in ways you will not notice until real data hits it. A missing anchor lets it match inside a larger string when you wanted the whole thing. An unescaped dot matches any character instead of a literal period. A greedy quantifier swallows far more than intended. None of these produce an error — the regex runs, returns something, and you move on, only discovering weeks later that it accepted a malformed value or dropped a valid one. This is why regex generated by AI needs verification more than most code, and why the prompt insists on an explanation and test cases rather than just the bare pattern. The goal is to make correctness visible instead of taking a clever-looking string on faith.
Flavor is not optional — the syntax genuinely differs
"Regex" is not one language. The dialect your tool speaks changes what is valid and what a pattern actually does. Lookbehind assertions work in modern JavaScript, Python, and PCRE but historically did not in JavaScript at all. Named groups use (?<name>...) in some flavors and (?P<name>...) in Python. Character class shorthands, Unicode handling, and even how backreferences are written vary between engines. A pattern copied from a PHP answer can fail silently or throw in a Go program because the two use different regex libraries with different feature sets. That is why the prompt makes you state the flavor up front — JavaScript, Python, PCRE, .NET, Go, or whatever you are targeting. Telling the model the engine changes which constructs it reaches for and which flags it recommends, and it prevents the maddening loop of pasting an error, getting a fix, and hitting the next dialect-specific difference.
Examples are the single biggest accuracy boost you can give
The most valuable thing in the prompt is not the description of what you want — it is the two lists of concrete strings that must match and must not match. A plain-English description like "match an email address" is hopelessly ambiguous: does it allow plus-addressing, subdomains, new top-level domains, quoted local parts? Every developer means something slightly different. When you instead hand the model five strings that should pass and five that should fail, you convert a fuzzy request into a precise specification. The model now has something to test its pattern against, and the prompt asks it to confirm the regex satisfies every example. This is also how you encode the edge cases that matter to you specifically — put the tricky legitimate value in the "must match" list and the near-miss you want rejected in the "must not match" list, and the pattern is forced to draw the line exactly where you need it rather than where the model guesses.
Verify the result, and watch for backtracking and readability
Even a well-specified pattern deserves a check before it ships. Run it against your own examples plus a few the model did not see, because a regex that passes its own test cases can still fail on inputs nobody thought to list. Two specific risks are worth naming, which is why the prompt calls them out. The first is catastrophic backtracking: certain patterns, especially nested quantifiers like (a+)+ applied to long non-matching input, can take exponential time and hang your program or open a denial-of-service hole. Asking the model to avoid it prompts safer construction. The second is readability. A regex you cannot read is a regex you cannot maintain, and six months from now that will be your problem. Prefer a slightly longer, clearer pattern — or one broken into named groups with comments where the flavor supports verbose mode — over a dense one-liner that no one dares touch. The explanation the prompt requests is not just for verification today; it is documentation for the next person who has to change it.
Why this prompt works
Regex is deceptively easy to get subtly wrong — a pattern can look right and still miss cases or match too much. This prompt pins down the flavor, gives the model real examples to satisfy, and returns a part-by-part explanation with test cases, so you can verify the pattern does exactly what you need instead of trusting an opaque string.
How to customize it
- Always specify the flavor; syntax differs across languages.
- Give both matching and non-matching examples to pin down intent.
- Test the pattern on real data before you deploy it.
Example output
Sample onlyNeed: Validate that a string is a price in the form of digits with an optional two-decimal part, optionally prefixed with a dollar sign. Flavor: JavaScript.
Must match: $12, $12.50, 0.99, 1000
Must not match: $12.5, 12., abc, $
Pattern: /^\$?\d+(\.\d{2})?$/
Explanation: ^ and $ anchor the whole string so nothing extra is allowed. \$? permits an optional literal dollar sign (the backslash escapes it). \d+ requires one or more digits. (\.\d{2})? optionally allows a decimal point followed by exactly two digits — so $12.5 and 12. are rejected. No flags are needed.
Check: All four "must match" strings pass; all four "must not match" strings fail, because a lone $ has no digits, abc is non-numeric, and the two decimal cases break the exact \d{2} rule.
Prompt variations to try
Explain an existing regex
You are a regex tutor. Explain this regular expression in plain English, part by part: [paste the regex] Flavor: [JavaScript / Python / PCRE / etc]. Requirements: - Break it into its components (anchors, character classes, groups, quantifiers, assertions) and explain what each does. - Give 3 example strings it matches and 3 it rejects, so the behaviour is concrete. - Point out anything surprising or risky — greedy quantifiers, missing anchors, or patterns prone to catastrophic backtracking. Assume I understand basic regex but not this specific pattern.
Debug a regex that matches too much or too little
You are a regex expert. This regex is not behaving correctly: [paste the regex] Flavor: [JavaScript / Python / etc]. What it should do: [describe intended behaviour]. It currently: [matches too much / matches too little / fails on these inputs]. Strings it wrongly matches: [list them]. Strings it wrongly rejects: [list them]. Requirements: - Diagnose why it's misbehaving (e.g. a greedy quantifier, missing anchor, or unescaped metacharacter). - Provide a corrected pattern and explain what changed. - Confirm the fix handles all the example strings correctly.
Convert a regex between flavors
Convert this regular expression from [source flavor] to [target flavor]: [paste the regex] Requirements: - Translate any flavor-specific syntax — named groups, lookbehind, shorthand classes, inline flags — to the target's equivalents. - List each change you made and why. - Flag anything that has no direct equivalent in the target flavor and suggest a workaround. - Confirm the converted pattern matches the same set of strings as the original.
Common mistakes to avoid
- Not stating the flavor. Regex syntax differs across engines, so a pattern for one language can fail or behave differently in another. Always say
JavaScript,Python,PCRE, or whatever you actually run. - Giving only a vague description. "Match an email" means something different to everyone. Provide concrete strings that must match and must not match so the pattern is pinned to your exact definition.
- Skipping the non-matching examples. A pattern that matches the right things but also matches wrong ones is broken. Listing what must be rejected is how you catch a regex that is too permissive.
- Trusting the pattern without testing. A regex can pass its own examples and still fail on real data. Run it against your own inputs, including a few the AI never saw, before deploying.
- Ignoring catastrophic backtracking. Nested quantifiers like
(a+)+can hang on long input and become a denial-of-service risk. Ask for a pattern that avoids it and prefers readability.
Frequently asked questions
Why does the AI need to know the regex flavor?
Because "regex" is really a family of dialects. Features like lookbehind, named-group syntax, and Unicode handling differ between JavaScript, Python, PCRE, .NET and others, so a pattern that works in one can fail or misbehave in another. Stating the flavor lets the model use the correct syntax and recommend the right flags.
How many examples should I give?
Aim for three to five strings that must match and three to five that must not. That range is enough to pin down your exact intent — including the tricky legitimate values and the near-misses you want rejected — without overwhelming the prompt. The more precisely your examples draw the line, the more accurate the pattern will be.
Can I trust an AI-generated regex in production?
Only after you test it. Regex is famously easy to get subtly wrong, so run the pattern against your own inputs — including edge cases the AI never saw — before shipping. Pay attention to the explanation and any backtracking warnings, and be cautious using it on untrusted user input where a slow pattern could be exploited.
What is catastrophic backtracking and why does it matter?
It's when a poorly constructed pattern — often nested quantifiers such as (a+)+ — takes exponential time to fail on certain inputs, freezing your program. On a public form it can even be a denial-of-service vector. Asking the model to avoid it, and testing with long non-matching strings, keeps your regex safe and fast.
Tip: replace the parts in [square brackets] with your own details before you send. The more specific you are — audience, tone, goal, constraints — the better the AI output.