Coding
AI Prompt for Fixing Broken Regex
Fix broken regex fast with this AI prompt: pinpoint the faulty piece, get a minimal corrected pattern, and verify it against all your test cases.
The prompt
Role: You are a regex surgeon who diagnoses and repairs broken patterns with minimal changes. Context: Regex flavor: [FLAVOR]. Broken pattern: [BROKEN_PATTERN] Symptom: [SYMPTOM, e.g. matches things it shouldn't, rejects valid input, hangs on long input] Failing test cases: [TEST_CASES] Task: 1) Diagnose: identify the exact piece of the pattern causing the symptom and explain WHY it misbehaves (precedence, greediness, missing anchor, wrong character class, etc.). 2) Provide the fixed pattern with the smallest possible change. 3) Verify the fix against all [TEST_CASES] plus 3 new edge cases you invent. 4) Explain the underlying regex concept I misunderstood, so I learn it. Format: Diagnosis first (with the culprit piece highlighted), then the fixed pattern, then the verification table, then the concept lesson. After the fix, ask the AI to generate three regression test cases specifically targeting the misunderstood concept, so the same mistake cannot slip back in during future edits. Constraints: Minimal change — do not rewrite a working pattern from scratch unless it is fundamentally wrong. Teach the concept, not just the fix.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[FLAVOR] [BROKEN_PATTERN] [SYMPTOM] [TEST_CASES]
Example input
FLAVOR=Python, BROKEN_PATTERN=r'(\d{3})-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4}', SYMPTOM=matches '123-456-7890' inside 'abc123-456-7890xyz' when it shouldn't, TEST_CASES=provided list of 6
How to use this prompt
Include the failing test cases — they define 'fixed' precisely. Describe the symptom in terms of wrong matches, not just 'it doesn't work'.
Tips for the best results
- The diagnosis section is the real prize — read it even if you only wanted the fix.
- Ask it to explain operator precedence if alternation (|) is involved — it is the #1 regex bug source.
- Save the concept lesson; regex mistakes repeat until the concept clicks.
Frequently asked questions
I have failing test cases already. Should I include them?
Yes — that is the ideal input. Broken regex + failing cases is the fastest path to a correct fix.
Should I just rewrite the regex from scratch?
Only if the diagnosis shows the pattern is fundamentally wrong. Minimal fixes preserve the parts that already work — and the lesson sticks better.