How to Write a Regex with ChatGPT: A Prompt Workflow

What You Will Deliver

This workflow turns a vague matching need into a correct, tested regular expression. By the end you will have a clear match spec, a working pattern, a set of test cases, edge-case handling, and a language-ready snippet. Expect 10 to 20 minutes per expression, less as you get used to the steps.

A free ChatGPT account is enough. The main failure mode is asking “write a regex to match emails” with no examples — the model guesses your format and misses edge cases. Instead, you give it concrete sample strings up front, then make it prove the pattern against tests. For why specific context beats vague asks in code work, see the vague vs specific coding prompts breakdown.

Step 1: Define the Match Spec with Examples

Before any pattern, state exactly what must match and what must not. Concrete examples are the single biggest lever on regex accuracy.

You are a regex expert. I need a pattern but first help me define the spec.
Goal: [WHAT YOU WANT TO MATCH, e.g. "US phone numbers"]
MUST match (give 3 to 5 real examples):
- [EXAMPLE 1]
- [EXAMPLE 2]
- [EXAMPLE 3]
MUST NOT match (give 2 to 3 examples):
- [NEGATIVE 1]
- [NEGATIVE 2]
List the rules a correct regex must follow, one per line, based only on these examples.

You get a precise rule list. This becomes the acceptance test for every pattern the model proposes later. If the examples contradict each other, fix them now.

Step 2: Generate the Pattern

Now request the actual regex, anchored to the spec you just wrote. Ask for an explanation so you can sanity-check it.

Using this spec: [PASTE RULE LIST FROM STEP 1]
Write a regular expression that matches the MUST-match examples and rejects the MUST-NOT-match examples.
Requirements:
- Use standard PCRE syntax unless I say otherwise.
- Explain each part of the pattern in plain English, grouped by token.
- State any assumptions you made.
Return the pattern on its own line, then the explanation.

You have a candidate pattern plus a token-by-token read. Read the explanation: if a token does something you did not ask for, note it. The ChatGPT coding settings guide covers model modes if you want more deterministic output.

Step 3: Build Test Cases

A pattern you have not tested is a pattern you do not trust. Ask the model to generate a balanced test set, then run it yourself in a regex tester.

For this regex: [PASTE PATTERN]
Generate 10 test strings:
- 5 that should MATCH (cover the examples and 2 tricky near-misses).
- 5 that should NOT match (cover the negatives and 2 edge cases).
Format as a table: Test string | Expected (MATCH/NOMATCH) | Reason.
Do not run the regex yourself; just predict the expected result.

You now have a test plan. Paste the pattern and each string into a tool like regex101 to confirm. Any failed row means the pattern or the spec needs a fix.

Step 4: Harden Edge Cases

Real data is messy. Push the model on boundaries: empty strings, extra whitespace, unicode, and anchoring. This step prevents silent mismatches in production.

Review this regex: [PASTE PATTERN]
Check these edge cases and tell me if the pattern handles each correctly:
1. Leading/trailing whitespace around the match.
2. Multiple matches in one line (should it match all or first only?).
3. Unicode or non-ASCII characters.
4. Case sensitivity — should it be case-insensitive?
5. Empty input.
For each, either confirm it is handled or propose a minimal fix (show the changed part only).

You get targeted fixes. Apply only the ones your real data needs. Over-anchoring a pattern to rare edge cases can break common matches, so choose deliberately.

Step 5: Port to Your Language

Regex syntax differs across languages. Get a drop-in snippet with the right flags and escaping for your stack.

Convert this regex: [PASTE FINAL PATTERN]
To a ready-to-use snippet in [LANGUAGE, e.g. Python / JavaScript / Go].
Include:
- The correct flag settings (e.g. case-insensitive, multiline).
- A one-line usage example with a sample input.
- A note on any escaping differences from PCRE.
Return only the code block and the one-line note.

You now have a language-specific snippet you can paste. The SQL query generator prompt uses the same “spec first, then code” idea if you build data tools next.

How the Steps Connect

Each stage feeds the next. The spec you write in Step 1 becomes the acceptance test for the pattern in Step 2. That pattern is then proven against the test cases from Step 3. A failed test sends you back to Step 2 or Step 4, never forward. Only once the pattern passes your examples do you harden edge cases and port to code. Because the spec is the anchor, a wrong example in Step 1 poisons every later stage, so invest the most care there. Keep all outputs in one note so you can re-paste context without re-explaining from scratch each time.

A quick example: say you need to match a US zip code. Step 1 pins the rule “five digits, optionally a dash and four more.” Step 2 yields \d{5}(-\d{4})?. Step 3 tests “90210” (match) and “9021” (no match). If a test fails, fix the pattern before touching code. By Step 5 you ship a Python re.compile(r”\d{5}(-\d{4})?”) that you actually trust rather than one you hope works.

Final Deliverable Checklist

ItemDone?
Match spec with MUST/MUST-NOT examples
Pattern in PCRE with token explanation
10 test strings (5 match, 5 not)
Edge cases reviewed (whitespace, unicode, case)
Language snippet with correct flags
Pattern verified in a live tester

Common Pitfalls

1. No examples in the prompt. The model guesses your format and misses edge cases. Always paste real sample strings.

2. Skipping the test step. An untested regex fails on the one input that matters. Build test cases every time.

3. Using greedy quantifiers blindly. “.*” can swallow too much; prefer non-greedy or character classes.

4. Wrong language flags. PCRE and JavaScript flags differ; confirm case-insensitivity and multiline per stack.

Sources & Notes

Prompts tested with ChatGPT (GPT-4o and GPT-4.1), free and Plus tiers, in October 2026. The workflow follows a five-stage delivery pattern (spec, pattern, tests, edge cases, port) and is model-agnostic — it also works in Claude or Gemini. Category mapping follows the guunn.com AI Prompts plan (Coding = 957). No live APIs were called during article creation; prompts are copy-paste text for the reader.

声明:1.本站所有文章,如无特殊说明或标注,均为本站原创发布。本网站中【文本生成/文生图】使用了DeeSseek人工智能生成内容技术, 算法来源说明:本网站未自行开发、训练或部署深度合成算法,所使用的人工智能算法来自:DeepSeek、Chatgpt、Google Gemini。 2.为了网站加载速度优化,本站预览图片进行压缩处理,所以有些不是太清晰,并不影响AI提示词生图、AI设计等内容。3.任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。--GUUNN.COM