Coding Prompts
Generate Regular Expression
Write a regex pattern for any text matching task, with explanation and test cases.
Prompt
Write a regular expression for use in [PROGRAMMING_LANGUAGE]. **Strings that SHOULD match:** [WHAT_TO_MATCH] **Strings that should NOT match:** [WHAT_NOT_TO_MATCH] **Constraints:** [CONSTRAINTS] Please provide: 1. **The regex pattern** — ready to copy and paste, formatted as a raw string or literal appropriate for [PROGRAMMING_LANGUAGE] 2. **Plain-English explanation** — describe what each part of the pattern does (break it down token by token for non-trivial patterns) 3. **Test cases** — a small code snippet that runs the pattern against all the provided match/no-match examples and prints the results
How to Use
Describe what you want to match using concrete examples rather than abstract rules — "match email addresses" is vague, but showing five real examples and two non-examples gives the model enough signal to write a precise pattern. Always test the generated regex against your real data before using it in production, since edge cases in text data are notoriously unpredictable.
Variables
| Variable | Description |
|---|---|
| [PROGRAMMING_LANGUAGE] | The language where the regex will run — this matters because flavors differ (e.g., Python, JavaScript, Go, Java, Ruby, PCRE). |
| [WHAT_TO_MATCH] | 3-5 concrete example strings that the pattern must match. Example: "user@example.com", "firstname.lastname@company.co.uk", "user+tag@sub.domain.org" |
| [WHAT_NOT_TO_MATCH] | 2-3 example strings the pattern must reject. Example: "notanemail", "@nodomain.com", "missing@.tld" |
| [CONSTRAINTS] | Specify matching behavior: full match (entire string) or partial match (find anywhere in string); multiline (yes/no); case-sensitive (yes/no); any character set or length restrictions |
Tips
- The more boundary cases you list in "should NOT match," the tighter and more precise the regex will be — vague counterexamples produce overly broad patterns.
- For complex patterns, ask for a verbose/commented version using the
xflag (Python/Ruby) or equivalent, which makes the pattern much easier to maintain later.