Skip to main content
Back to Library
Prompt Engineering Guide

Mastering Regular expression writing
on GPT-4o

Stop guessing. See how professional prompt engineering transforms GPT-4o's output for specific technical tasks.

The "Vibe" Prompt

"Write a regular expression to match email addresses."
Low specificity, inconsistent output

Optimized Version

STABLE
You are an expert in regular expressions with a deep understanding of common email address patterns and edge cases. Your task is to write a regular expression. **Constraint Checklist:** - Must validate standard email formats (e.g., user@domain.com, user.name@sub.domain.co). - Should not allow leading/trailing dots or consecutive dots in the local part. - Should not allow leading/trailing hyphens or consecutive hyphens in the domain part. - Should allow common special characters in the local part (e.g., !, #, $, %, &, ', *, +, -, /, =, ?, ^, _, `, {, |, }, ~). - The domain must have at least one dot (e.g., example.com). - The top-level domain (TLD) must be at least 2 characters long. **Chain of Thought (CoT) Strategy:** 1. **Local Part Analysis:** Break down valid and invalid characters and structural rules for the username before the '@'. Consider common special characters and dot placement. 2. **Domain Part Analysis:** Break down valid and invalid characters and structural rules for the domain after the '@'. Consider subdomains, hyphens, and dot placement. 3. **TLD Validation:** Ensure the TLD meets length requirements. 4. **Combine and Refine:** Synthesize the local part, '@' symbol, and domain part into a single regex. Review against all constraints and edge cases. **Final Regular Expression:**
Structured, task-focused, reduced hallucinations

Engineering Rationale

The optimized prompt leverages a chain-of-thought to guide the model through the complex task of regex construction for email validation. It explicitly lists constraints, ensuring all requirements are considered. By outlining a CoT strategy, it forces GPT-4o to break down the problem into manageable steps (local part, domain part, TLD), which improves the accuracy and completeness of the resulting regex. The introductory role-play ('expert in regular expressions') primes the model for a high-quality output. The structure makes it less likely to miss edge cases compared to a vague, open-ended request.

0%
Token Efficiency Gain
The generated regex must correctly identify 'test@example.com'.
The generated regex must reject 'test@example'.
The generated regex must reject '.test@example.com'.

Ready to stop burning tokens?

Join 5,000+ developers using Prompt Optimizer to slash costs and boost LLM reliability.

Optimize My Prompts