Coding
AI Prompt for Generating Regex
Generate correct regex from plain English with this AI prompt: flavor-specific pattern, piece explanations, and match/no-match verification tables.
The prompt
Role: You are a regex craftsman who writes precise, readable patterns and proves they work. Context: Regex flavor: [FLAVOR: JavaScript / Python / PCRE / Java / etc.]. What to match: [DESCRIPTION] Must match: [MUST_MATCH_EXAMPLES] Must NOT match: [MUST_NOT_MATCH_EXAMPLES] Task: 1) Write the regex for [FLAVOR]. 2) Explain each part of the pattern briefly. 3) Verify it against every must-match and must-not-match example, showing the result for each. 4) Warn about performance traps (catastrophic backtracking) if any exist, and provide a safe alternative if needed. Format: Pattern in a code block first, then the explanation, then a verification table (example | expected | actual | pass/fail), then any warnings. Ask the AI to also provide the pattern WITHOUT capture groups if you only need validation, since unused groups cost performance and complicate the match object. Small hygiene, real savings at scale. Constraints: Optimize for correctness and readability over cleverness. If the requirement is ambiguous, state your assumption explicitly instead of guessing silently.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[FLAVOR] [DESCRIPTION] [MUST_MATCH_EXAMPLES] [MUST_NOT_MATCH_EXAMPLES]
Example input
FLAVOR=JavaScript, DESCRIPTION=match US phone numbers like (555) 123-4567 or 555-123-4567, must not match 5551234567 without separators, STRICTNESS=reject invalid area codes starting with 0/1
How to use this prompt
Describe what should match AND what must not match — exclusions are where regex specs fail. Include 2-3 real examples of each.
Tips for the best results
- Always include must-NOT-match examples — they catch 80% of regex bugs.
- Ask for a non-regex alternative when the pattern gets too complex to read.
- Test the final pattern in a regex tester with your real data before deploying.
Frequently asked questions
How do I know the regex actually works?
It generates the pattern plus match/no-match tests — paste your real data and ask it to verify before you ship.
What if my description is ambiguous?
The prompt states its assumptions explicitly instead of guessing silently. Correct the assumption and regenerate — two quick iterations beat one vague pattern.