Best ChatGPT Prompt for Regex
Write the regex you need, understand the one you have, and stop guessing at character classes.
The Prompt
You are a senior engineer who has written regular expressions in production for 15 years across Python, JavaScript, Go, grep, and sed. Help me with a regex task. Regex flavor: [PCRE / JavaScript / Python re / Go / POSIX / grep / etc.] What I'm trying to match: [DESCRIBE IN PLAIN ENGLISH — be specific about what counts and what doesn't] Sample inputs that SHOULD match: [PASTE 3-5 EXAMPLES] Sample inputs that should NOT match: [PASTE 3-5 EXAMPLES — the edge cases that trip up bad regex] Requirements: - Give me the regex pattern, in the exact flavor I specified - Walk through it character-by-character so I understand what each piece does - Show me the gotchas (greedy vs lazy, anchoring, escaping in this flavor) - If a non-regex approach (string methods, parser) would be safer, say so first - If my requirement is ambiguous, ASK before guessing — don't write a regex that almost works
How to Use This Prompt
- Copy the prompt and specify your regex flavor
- Always paste 3-5 should-match AND 3-5 should-NOT-match examples — without negatives the regex will overmatch
- Describe the rule in plain English first (“US phone numbers with optional country code”), not regex shorthand
- Paste into ChatGPT or Claude
- Test the regex against ALL your examples before shipping — regex bugs hide in the cases you didn't think of
The single biggest mistake people make is giving only positive examples. The model will write a regex that matches those but also matches a lot you didn't intend. Always include the things that should NOT match.
Example Output
Task: Match US phone numbers with optional country code and parentheses
Response:
Pattern (PCRE / Python re):
^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
Walkthrough:
^ Anchor: start of string
(?:\+?1[-. ]?)? Optional country code: +1, 1, +1-, 1., etc.
\(? Optional opening paren
([0-9]{3}) Capture group 1: area code
\)? Optional closing paren
[-. ]? Optional separator: -, ., space
([0-9]{3}) Capture group 2: prefix
[-. ]? Optional separator
([0-9]{4}) Capture group 3: line number
$ Anchor: end of string
Gotcha: if your input is multiline and you want to match per-line, use re.MULTILINE
and ^ / $ will anchor to line boundaries.
Tips to Get Better Results
- Test against the negatives first. Run the regex on your should-NOT-match examples. If any match, the regex is wrong — even if all the should-match cases pass.
- Specify the flavor. JavaScript regex doesn't support lookbehinds the same way Python does. Python's re is different from PCRE. Tell the model which one.
- Ask for a non-regex alternative. For HTML, JSON, and CSV, regex is the wrong tool — use a parser. A good prompt response will say so.
- Iterate with new edge cases. After it gives you a pattern, throw a weird input at it (“what about an extension like x1234?”) and ask it to handle.