Magic Tools
AI TutorialsBy CooconApril 22, 2026312 views4 min read

How to Use ChatGPT to Write Regular Expressions (2025)

Writing regex by hand is painful. ChatGPT makes it fast. This article shows you exactly how to get useful, working regex patterns from ChatGPT — with real examples you can use today.


Step 1: Describe What You Want to Match

Don't open with "write me a regex." That's too vague. Instead, describe the input and what you want to extract or validate.

Bad prompt:

Write a regex for emails.

Good prompt:

Write a regex that matches email addresses.
The email must have a local part, an @ symbol, a domain name, and a TLD like .com or .org.
Example valid input: hello@example.com
Example invalid input: hello@, @example.com

ChatGPT will give you something like:

^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$

That's a solid starting point. You don't need to understand every character — just test it against your real data.


Step 2: Give It Edge Cases

The first regex is rarely perfect. You need to push it with examples that break things.

Say you're trying to match US phone numbers. You ask ChatGPT and it gives you:

^\d{3}-\d{3}-\d{4}$

That matches 555-867-5309. But what about (555) 867-5309 or 5558675309? Those are valid too.

Go back to ChatGPT with this:

Update this regex to also match these formats:
- (555) 867-5309
- 555.867.5309
- 5558675309
- +1 555 867 5309

Current regex: ^\d{3}-\d{3}-\d{4}$

You'll get something much more flexible:

^(\+1\s?)?(\(?\d{3}\)?[\s.\-]?)\d{3}[\s.\-]?\d{4}$

This is the loop: get a regex, test it, find what breaks, go back with specific examples. Two or three rounds usually gets you there.


Step 3: Ask for an Explanation

Once you have a working regex, ask ChatGPT to break it down.

Explain this regex line by line:
^(\+1\s?)?(\(?\d{3}\)?[\s.\-]?)\d{3}[\s.\-]?\d{4}$

ChatGPT will tell you exactly what each part does:

  • ^ — start of string
  • (\+1\s?)? — optional +1 country code with optional space
  • \(? — optional opening parenthesis
  • \d{3} — exactly three digits

You don't need to memorize regex syntax. You just need to understand the pattern well enough to describe changes to ChatGPT.


Three Prompt Templates You Can Copy Right Now

Template 1 — Validation

Write a regex that validates [what you're validating].
Rules:
- [rule 1]
- [rule 2]
Give me the regex and a short explanation of what each part does.
Example valid: [your example]
Example invalid: [your example]

Template 2 — Extraction

Write a regex to extract [what you want to extract] from this text:

[paste a sample of your actual text here]

I'm using [Python / JavaScript / Go / PHP] — make sure the syntax works for that language.

Template 3 — Fix My Regex

This regex isn't working the way I expect:
[your current regex]

It should match: [example that should match]
It should NOT match: [example that shouldn't match]
Right now it's [what's going wrong].
Fix it and explain what you changed.

These three templates cover 90% of what you'll ever need.


FAQ

Does ChatGPT always get regex right the first time?

Not always. ChatGPT is good at common patterns like emails, URLs, and phone numbers, but it can miss edge cases on the first try. Always test the output against real data before using it in production. The feedback loop — test, break, ask again — is what makes it work.

Which regex flavor should I specify?

It depends on your language. Python uses the re module (PCRE-like). JavaScript has its own engine with some differences. Go's regex doesn't support lookaheads. Always tell ChatGPT which language you're working in so it avoids syntax that won't work in your environment.

Can ChatGPT write regex for complex multi-line text?

Yes, but you need to say so explicitly. Add something like "this is multi-line input, use the appropriate flags" to your prompt. In most languages, you'll also need to enable multiline or dotall mode when you use the regex.

Is it safe to use ChatGPT-generated regex in production?

With testing, yes. Run it against a good set of examples that cover your real-world inputs. If the pattern is security-sensitive, also check it for ReDoS vulnerabilities, which ChatGPT can help you spot if you ask.

What if I need to match something very domain-specific?

Paste in real examples. ChatGPT learns from what you show it, not from your description alone. If you're matching internal log file formats or anything non-standard, paste 5–10 real examples directly into the prompt.


Test Your Regex Before You Ship It

Once you have a pattern, don't just run it in production and hope for the best.

MagicTools Regex Tester lets you paste your regex and test it against multiple lines of input instantly. You can see which parts of the string are captured, which groups match, and catch mistakes before they cause problems. It's free and works right in your browser — no setup needed.

Write the regex with ChatGPT, test it there, iterate if needed. That's the whole workflow.

Related Articles

Blocking rm -rf in Claude Code: A Deny Rule Stopped 14 Deletes in Two Weeks, 7 Other Spellings Still Get Through, and a Hook That Closes the Gap

To keep Claude Code from deleting things by accident, I added a deny rule, Bash(rm -rf *), to my global settings. Across my sessions from October 7 to 21 it blocked 14 deletes. After each denial the model picked a new directory name 8 times and dropped the delete 6 times. It never tried another spelling. Then I replayed 22 delete commands verbatim against Claude Code 2.1.285 through a stub. rm -fr, rm -r -f, rm -Rf and rm -r deleted the directory in manual, auto and bypass mode alike. /bin/rm, find -delete and bash -c deleted it in manual and bypass mode. In auto mode, rm -fr inside the working directory skips the classifier because it 'would be allowed in acceptEdits mode'. A second, built-in dangerous-rm check fires on targets like $D/*, even in bypass mode, but loses track of a variable assignment when a heredoc comes earlier in the same command. The post ends with a PreToolUse hook that blocks every recursive spelling in all three modes and tells the model what to do instead.

claude-codehooks+5
pitfallsOct 21, 20268 min
208

The Self-Reinforcing Flywheel Is Harder Than It Looks: 40 Days of an LLM Auto-Tuning Loop

We ran an 'LLM proposes, code decides' auto-tuning loop on a daily WeChat newsletter for 40 days: 18 versions, 8 rollbacks. Three of those rollbacks overturned decisions a human had made, and one version whose knobs were identical to its parent still got rolled back. Using our real numbers, telling apart a 20% difference needs about 25,000 reads per version. At 60 reads a day, that is more than 400 days. This postmortem covers five reasons the flywheel never turned, and what actually moved the numbers.

wechatpostmortem+4
pitfallsOct 21, 20268 min
133

Dev Breakfast · 2026-10-21

Today's headline: A single "bonsoir, Elliot" makes the model leak its .env: a backdoor for under $50. Plus 4 more: DeepSeek open-sources its inference engine: V4.1 Flash only, and KV cache still missing; TorchTPU goes open source: PyTorch models can run directly on TPU; and more.

daily-intelOct 21, 20268 min
446

Dev Breakfast · 2026-10-20

Today's headline: Should You Merge AI Code You Don't Understand: Settle the Abstraction Layer Yourself First. Plus 4 more: tmux as a Remote Control: Multi-Session Claude Code and send-keys; headroom Goes Open Source: 95% Token Savings on JSON, Only 20% for Coding Agents; and more.

daily-intelOct 20, 20265 min
415

Published by Magic Tools