The most reliable way to get a working regular expression from an AI model is to give it examples, not just a description: 3 to 5 strings that must match, a few near-misses that must not, the exact regex flavor (Python, JavaScript, PCRE, Go and so on), and whether the pattern must match the whole string or find text inside a longer one. Then test the result against those examples and your real data before using it. The prompts below cover writing, explaining, simplifying, debugging and hardening a regex, each with notes on why every line is there.
Image: Oboy2009, Wikimedia Commons, licensed under CC BY-SA 4.0.
A regular expression (regex) is a pattern language for matching text. It is compact, unforgiving and different in small ways between languages, which is exactly why AI help is useful and why unchecked AI output is risky.
Why regex prompts need examples, not descriptions
A description like “write a regex for a phone number” hides dozens of decisions the model has to guess. Which country? Are spaces, dashes, dots or parentheses allowed? Is the country code optional? Should extensions match? Must the string contain only the phone number, or is it embedded in a sentence? The model picks an answer for each, and you only discover its choices when real data fails.
Examples answer those questions without you having to list them. Positive examples show the variety the pattern must accept. Negative examples, especially near-misses that are almost valid, show where the boundary is. This is few-shot prompting applied to pattern design; our comparison of zero-shot vs. few-shot prompting explains why examples steer output more precisely than instructions alone.
The five details every regex prompt should include
| Detail | Why it matters | Example wording |
|---|---|---|
| Flavor and version | Syntax and features differ: Python’s named groups use (?P<name>...), JavaScript uses (?<name>...); Go’s RE2-based engine has no lookarounds or backreferences | “Python 3.12 re module” |
| Match mode | Validation needs the whole string to match; extraction finds matches inside text | “Used with re.fullmatch to validate a form field” |
| Must-match examples | Show the real variety of valid input | 3-5 strings, including the unusual valid ones |
| Must-not-match examples | Define the boundary; prevent overly permissive patterns | 3-5 near-misses, one rule broken in each |
| Input source | User input needs protection against slow patterns; trusted logs may not | “Input comes from a public web form, max 200 characters” |
Prompt 1: Write a regex from examples
The writing prompt combines all five details and asks for a pattern plus an explanation and a self-check. The illustrative case below is a product SKU format: three uppercase letters, a dash, four digits, and an optional two-letter color suffix.
Write a regular expression for Python 3.12 (re module).
It will be used with re.fullmatch() to validate a single form field.
Input comes from users; max length 20 characters.
Must match:
ABC-1234
XYZ-0042-BL
QRS-9999-GR
Must NOT match:
abc-1234 (lowercase letters)
ABC-123 (only three digits)
ABC-1234-B (one-letter suffix)
ABC-1234-BLU (three-letter suffix)
ABCD-1234 (four letters)
ABC-1234 (leading space)
Return:
1. The pattern as a Python raw string.
2. A one-line explanation of each part.
3. A table showing each example above and whether your pattern matches it.
4. Any input you think is ambiguous given these examples.
Why each part is there: the flavor line prevents syntax from the wrong engine. Naming re.fullmatch() tells the model that anchoring is handled, or that it should add ^ and $ if you use a different function. Each near-miss breaks exactly one rule, which pins down each boundary. The self-check table forces the model to walk through every example instead of asserting that the pattern works, and the ambiguity question surfaces cases your examples did not cover.
A correct answer for this example is ^[A-Z]{3}-\d{4}(?:-[A-Z]{2})?$. The (?:...) is a non-capturing group, used because the suffix only needs grouping for the ?, not capturing. That pattern matches all three valid examples and rejects all six near-misses; still run it yourself rather than trusting the model’s table.
A note on \d and Unicode
In Python 3 string patterns, \d matches any Unicode decimal digit, not only 0-9, so it would accept digits from other scripts. If only ASCII digits are valid, ask for [0-9] or the re.ASCII flag. This is the kind of detail a model may not mention unless you ask “what non-ASCII input would this accept?”.
Prompt 2: Extract fields from log lines with named groups
Extraction prompts should ask for named groups so the code that uses the pattern stays readable. The example parses an illustrative application log format.
Write a Python 3.12 regex to parse each line of this log format into named groups:
ts, level, req, msg. I will apply it per line with re.fullmatch().
Lines that must parse:
2026-10-24T09:15:02Z WARN [req=7f3a9c] payment retry scheduled
2026-10-24T09:15:03Z ERROR [req=00b1e4] card declined: insufficient funds
Lines that must NOT parse:
2026-10-24T09:15:02Z WARNING [req=7f3a9c] x (level not in DEBUG|INFO|WARN|ERROR)
2026-10-24 09:15:02Z INFO [req=7f3a9c] x (space instead of T)
2026-10-24T09:15:02Z INFO [req=7F3A9C] x (uppercase hex)
2026-10-24T09:15:02Z INFO [req=7f3a9] x (5 hex chars)
2026-10-24T09:15:02Z INFO [req=7f3a9c] (no message)
Return the pattern in re.VERBOSE form with a comment on each line,
then the same pattern on one line.
Asking for re.VERBOSE is a maintenance choice. The Python re documentation explains that verbose mode ignores whitespace and lets # start a comment, so a long pattern can be documented line by line. A pattern that satisfies the examples above is:
LOG_LINE = re.compile(r"""
^(?P<ts>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z) # ISO 8601 UTC timestamp
\ (?P<level>DEBUG|INFO|WARN|ERROR) # fixed set of levels
\ \[req=(?P<req>[0-9a-f]{6})\] # 6 lowercase hex chars
\ (?P<msg>.*)$ # rest of the line
""", re.VERBOSE)
Note the escaped spaces (\ ): in verbose mode, a plain space is ignored, a detail models sometimes get wrong when converting a one-line pattern. If you are designing the log format itself, our prompts for error messages and log output help make lines easier to parse in the first place.
Prompt 3: Explain a regex someone else wrote
An explanation prompt is useful when you inherit a pattern and need to know what it really accepts before changing it. The key instruction is to explain without modifying, then prove the explanation with examples.
Explain this JavaScript regex piece by piece. Do not change it.
/^(?=.*[A-Z])(?=.*\d)[\w!@#$%]{8,64}$/u
1. Break it into tokens and explain each one in plain English.
2. Describe in one sentence what strings it accepts overall.
3. Give 5 strings it matches and 5 near-misses it rejects, including at least one
string a reader would probably expect to match but that is rejected.
4. List anything that looks like a mistake or an unintended permission.
The request for a surprising rejection is the valuable part. In this example, the character class has no space and no symbols beyond !@#$%, so a password containing & or a space is rejected, which may or may not be intended. Explanation-first prompts expose that kind of decision before someone “fixes” the pattern and changes behavior for every user.
Prompt 4: Simplify an overcomplicated regex
A simplification prompt should require behavior equivalence and make the model list any differences. Without that rule, “simpler” often means “matches something different”.
Simplify this Python regex while matching exactly the same set of strings:
[paste pattern]
Rules:
- Same flavor (Python re), same flags, same capture groups in the same order
unless I say otherwise.
- If an exactly equivalent simpler version is not possible, say so and give the
closest version with a list of every input where behavior differs.
- Return a test list of at least 10 strings, with the expected result for the
original and the simplified pattern side by side.
Keeping capture groups stable matters because code elsewhere often reads group(2); removing a group silently shifts the numbering. Then run both patterns over your test list and your real data, and compare results in code rather than by eye.
Prompt 5: Port a regex between languages
Regex flavors share most syntax but differ in important features, so porting needs an explicit compatibility check. Go’s standard library and other RE2-based engines are the common trap: the RE2 syntax reference marks backreferences and all lookahead and lookbehind forms as not supported.
Port this regex from JavaScript (with flags /giu) to Go's regexp package:
[paste pattern]
1. List every feature in the original that Go's RE2 syntax does not support.
2. For each, give the Go-compatible alternative, or say it needs code outside the
regex (for example a second check in Go).
3. Map each JavaScript flag to Go's equivalent inline flag, or explain the difference.
4. Give the final Go pattern as a raw string literal, plus 5 test inputs with
expected results in both languages.
The same structure works for any pair: JavaScript to Python (named group syntax changes), Python to PostgreSQL, or PCRE to .NET. For JavaScript specifics, MDN’s regular expressions reference lists the flags, including v (unicodeSets), an upgrade to u mode, and d, which generates match indices.
Prompt 6: Check a regex for catastrophic backtracking
Catastrophic backtracking happens when a backtracking regex engine tries an exponential number of paths on input that almost matches, which can freeze a request thread for seconds or longer. When an attacker supplies that input on purpose, it is called ReDoS (regular expression denial of service). The OWASP ReDoS page describes the risky shape: a repeated group that contains its own repetition or overlapping alternatives, as in (a+)+$ or (a|aa)+$.
Review this regex for catastrophic backtracking. It runs on untrusted user input
in Python 3.12 (a backtracking engine).
[paste pattern]
1. Identify any nested quantifiers, quantified groups with overlapping
alternatives, or adjacent quantified tokens that can match the same characters.
2. For each, construct an input that would cause excessive backtracking,
and explain why.
3. Rewrite the pattern to remove the risk while matching the same valid inputs.
Prefer making repeated parts mutually exclusive; possessive quantifiers or
atomic groups (Python 3.11+) are acceptable if needed.
4. Recommend an input length limit for this field.
Python 3.11 added possessive quantifiers (*+, ++) and atomic groups ((?>...)), which stop the engine from backtracking into a part of the pattern, according to the re module documentation. Rewriting so repeated parts cannot overlap is usually clearer, and a length limit on the input is a cheap second defense. For a full review process before merging, use our pre-merge checklist for AI-generated regex.
Turn the examples into tests
Every example you wrote for the prompt is already a test case, so keep them in your codebase next to the pattern. That turns a one-off AI answer into something that stays correct when someone edits the pattern later.
import re
import pytest
SKU = re.compile(r"^[A-Z]{3}-[0-9]{4}(?:-[A-Z]{2})?$")
@pytest.mark.parametrize("value", ["ABC-1234", "XYZ-0042-BL", "QRS-9999-GR"])
def test_sku_valid(value):
assert SKU.fullmatch(value)
@pytest.mark.parametrize("value", [
"abc-1234", "ABC-123", "ABC-1234-B", "ABC-1234-BLU", "ABCD-1234", " ABC-1234",
"ABC-1234\n",
])
def test_sku_invalid(value):
assert not SKU.fullmatch(value)
The "ABC-1234\n" case is worth keeping: in Python, $ can match just before a trailing newline, so a pattern used with re.search() or re.match() may accept it, while fullmatch() does not. You can also ask the model to generate these tests directly; our guide to AI prompts for writing unit tests covers that workflow.
Common mistakes with AI-generated regex
- Missing anchors. A validation pattern without
^...$(or withoutfullmatch) accepts any string that merely contains a valid value. - Wrong flavor syntax. Lookbehind in Go,
(?P<name>)in JavaScript, or variable-width lookbehind in Python, which requires fixed width. - Unescaped dots.
.matches any character; a version pattern like1.2.3also matches1a2b3. - Greedy
.*in extraction. It can swallow several fields at once; ask for.*?or a negated class like[^"]*. - Regex for jobs regex cannot do. A pattern can check that an email address is shaped plausibly, but not that it exists or receives mail; confirm by sending a message. For structured formats like HTML, JSON or URLs, use a parser.
- Trusting the model’s own match table. Models can state that a pattern matches an example when it does not. Run the examples.



