Back to cookbook

AI Prompt to Generate a Regular Expression From a Plain-English Description

0 views Updated

Make this prompt yours

Share

This regex generator prompt is for developers who know exactly what pattern they need to match but don't want to hand-write and debug regex syntax from scratch. Instead of staring at a reference sheet, you describe the matching rule in plain English — "match US phone numbers with optional area code parentheses" — and ask ChatGPT, Claude, or Gemini to produce the regular expression along with an explanation of each part.

The prompt below is built to get more than just a pattern back. It asks the model to explain what each group or symbol does, test the pattern against both valid and invalid example strings you provide, and flag any edge cases your plain-English description didn't account for, like Unicode characters, extensions, or multiple formatting variants. That last part matters: a regex that works on your three test cases but silently fails on a slightly different real-world input is a common source of production bugs.

Regex, by nature, is full of edge cases that are easy to describe loosely and hard to get exactly right, so before you drop a model-generated pattern into production code, running the filled-in prompt through Prompt Debugger is a useful extra step — it's built specifically to catch vague constraints and missed edge cases in a prompt before you rely on its output.

Prompt template

Make this prompt yours

prompt-template
243 tokens
ROLE: You are a regular expression expert who writes precise, well-documented patterns. CONTEXT: I need a regular expression for this matching rule: [DESCRIBE WHAT THE PATTERN SHOULD MATCH IN PLAIN ENGLISH]. Target regex flavor/language: [E.G., JAVASCRIPT, PYTHON RE, PCRE, POSIX]. Strings that SHOULD match: [LIST 3-5 EXAMPLE STRINGS] Strings that should NOT match: [LIST 3-5 EXAMPLE STRINGS] TASK: 1. Write a regular expression that matches all the "should match" strings and rejects all the "should not match" strings. 2. Break down the pattern piece by piece, explaining what each group, anchor, and character class does. 3. Test the pattern mentally against every example I gave and confirm the result for each. 4. List any realistic edge cases my examples didn't cover that could still break this pattern, and note how the pattern handles them. OUTPUT FORMAT: - The regex pattern in a code block - A numbered breakdown of each part of the pattern - A table confirming match/no-match for each example string - A short "Edge cases to watch for" list

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
291 tokens
ROLE: You are a regular expression expert who writes precise, well-documented patterns. CONTEXT: I need a regular expression for this matching rule: match US phone numbers that may or may not have the area code in parentheses, and may use dashes, dots, or spaces as separators. Target regex flavor/language: JavaScript. Strings that SHOULD match: (555) 123-4567 555-123-4567 555.123.4567 5551234567 555 123 4567 Strings that should NOT match: 55-123-4567 555-12-4567 call 555-123-4567 ext 22 +44 20 7946 0958 TASK: 1. Write a regular expression that matches all the "should match" strings and rejects all the "should not match" strings. 2. Break down the pattern piece by piece, explaining what each group, anchor, and character class does. 3. Test the pattern mentally against every example I gave and confirm the result for each. 4. List any realistic edge cases my examples didn't cover that could still break this pattern, and note how the pattern handles them. OUTPUT FORMAT: - The regex pattern in a code block - A numbered breakdown of each part of the pattern - A table confirming match/no-match for each example string - A short "Edge cases to watch for" list

When to use it

  • You know the matching rule conceptually but don't want to hand-write regex syntax from memory
  • You're validating user input (emails, phone numbers, postal codes) and need a pattern that handles real-world format variations
  • You're extracting specific substrings (IDs, dates, tags) from log files or text with a predictable but awkward structure
  • You inherited a regex pattern from someone else's code and need a plain-English explanation of what it actually matches

Best practices

  • Give the model at least 3-5 example strings that SHOULD match and 3-5 that should NOT match, not just a description
  • Specify which regex flavor you need (JavaScript, Python, PCRE, POSIX) since syntax for things like lookaheads differs between them
  • Ask explicitly for a plain-English breakdown of each capture group so you can maintain the pattern later without reverse-engineering it
  • Test the generated pattern against your own real data, not just the examples you gave the model, since edge cases outside your examples are exactly where regex tends to break

Common mistakes

  • Describing the rule too loosely ("match an email") instead of specifying the exact edge cases you care about (subdomains, plus-addressing, uppercase)
  • Not telling the model which regex engine or language you're using, leading to syntax that doesn't work in your actual codebase
  • Treating the model's explanation as proof the pattern is correct instead of actually running it against real test data
  • Asking for one all-purpose pattern when the task really needs two simpler patterns combined in code

FAQs

Why does my regex work on some inputs but fail on others that look similar?

This almost always means your pattern was written to match only the examples you tested, not the full range of real-world variants. Giving the model both matching and non-matching examples up front, and asking it to call out uncovered edge cases, catches most of these gaps before the pattern ships.

Can ChatGPT or Claude write regex for any language or regex flavor?

Yes, but you need to specify which one (JavaScript, Python's re, PCRE, POSIX, etc.), since features like lookaheads, named groups, and escaping rules differ between flavors, and a pattern valid in one may throw a syntax error in another.

Is it safe to use an AI-generated regex in production without reviewing it?

No — always test it against your own real data, not just the examples in the prompt, since regex is notorious for passing a handful of test cases while silently failing on inputs nobody thought to check.

What tool can help me check this prompt's quality before using it?

Prompt Debugger — it scans a prompt for vague constraints and missed edge cases, which is exactly where regex-generation prompts tend to go wrong.

Found this prompt useful? Share it.

Share

More in Code Generation & Software Engineering

Code Generation & Software Engineering

AI Prompt to Turn a Linear Ticket Into an Implementation Plan Using Linear's MCP Server

This prompt turns a raw Linear ticket into a concrete implementation plan before any code gets written. It's built for developers and tech l…

ROLE
You are a senior software engineer producing an implementation plan from a project management ticket before any code is written.

CONTEXT
- Ticket source: Linear, accessed via the connected MCP server
- Ticket ID or URL: [TICKET_ID_OR_URL]
- Target repository or service: [REPO_OR_SERVICE_NAME]
- Relevant tech stack: [LANGUAGE_FRAMEWORK_STACK]

TASK
1. Read the ticket's title, description, comments, labels, and any linked parent or sub-issues from the connected Linear MCP server.
2. Summarize the current requirements in 3-5 sentences, noting anything that changed from the original description.
3. Propose an implementation approach: the files or modules likely affected, in order of change.
4. List edge cases and error conditions the implementation must handle.
5. List open questions that should be posted back to the ticket before work starts.

CONSTRAINTS
- Do not invent requirements that are not stated in the ticket or its comments.
- If acceptance criteria are missing or ambiguous, say so explicitly instead of assuming an answer.
- Keep the file/module list specific to what the ticket's labels and linked repo indicate; do not list unrelated parts of the codebase.
- Flag any blocking dependency on another open ticket.

OUTPUT FORMAT
## Ticket Summary
[3-5 sentence summary]

## Implementation Approach
- [Ordered list of files/modules and what changes in each]

## Edge Cases
- [List]

## Open Questions
- [List, or "None" if genuinely none]

Make this prompt yours

Code Generation & Software Engineering

AI Prompt to Triage Production Errors Using Sentry's MCP Server

This AI prompt is for developers and on call engineers who connect an AI assistant to Sentry's MCP server and want a fast, consistent first…

ROLE: You are a software engineer triaging production error reports retrieved through Sentry's MCP integration.

CONTEXT:
- Project: [PROJECT NAME]
- Time window: [E.G. LAST 24 HOURS]
- Current release/deploy: [VERSION, DEPLOY TIME]
- Known pre-existing low-priority issues to exclude: [LIST OR 'NONE']

TASK:
1. Retrieve open issues for the specified project and time window via the MCP connection, including stack trace, event count, affected users, and first-seen timestamp.
2. Group issues that share the same root exception type and call path as a single item.
3. For each grouped issue, state what the stack trace shows is happening, which file/function is implicated, and your confidence level in that read (high/medium/low).
4. Rank issues by severity using event count, affected user count, and whether first-seen falls after the stated deploy time.
5. Exclude any issue listed as a known pre-existing low-priority issue, but note it was excluded.

CONSTRAINTS:
- Do not propose a specific code fix; describe what the trace indicates and flag it for the responsible engineer.
- Do not rank an issue as high severity solely because of the error message tone; use the stated metrics.
- If stack trace data is incomplete or truncated, say so instead of inferring the missing frames.

OUTPUT FORMAT:
- Triage Summary (total issues reviewed, number flagged as new since deploy)
- Ranked Issue List (issue title, severity, event count, affected users, confidence in root cause read)
- Excluded Known Issues (if any)
- Issues Needing Manual Trace Review (low-confidence reads)

Make this prompt yours

Code Generation & Software Engineering

AI Prompt to Review Pull Requests for Bugs and Security Using GitHub's MCP Server

This prompt gives developers and engineering leads a repeatable way to review pull requests for bugs, security issues, and style problems by…

Role: You are a senior code reviewer with access to a GitHub MCP connection.

Context:
- Repository: [REPO_NAME]
- Pull request: [PR_NUMBER]
- Primary language/framework: [LANGUAGE_OR_FRAMEWORK]
- Team coding standards: [LIST_KEY_STANDARDS_OR_LINT_RULES]

Task:
1. Pull the current diff, changed file list, and CI status for the specified pull request.
2. Review the changes for: functional bugs, security issues (e.g. unvalidated input, hardcoded secrets, injection risks), and violations of the team's coding standards.
3. Note any missing or inadequate test coverage for the changed code.

Constraints:
- Base feedback only on the actual diff and files pulled from the repository, not assumptions about unseen code.
- Separate findings into "Blocking" and "Suggestion" categories.
- Reference the specific file and line number for each finding.
- Do not approve, merge, or close the pull request; this review is advisory only.

Output format:
- Summary: one paragraph on overall PR readiness
- Blocking issues: bulleted list with file:line and explanation
- Suggestions: bulleted list with file:line and explanation
- Test coverage notes: bulleted list

Make this prompt yours