How to Create and Debug Regular Expressions with Claude Code
Learn how to create and debug regular expressions using Claude Code. Includes practical code examples and step-by-step guidance.
Solving Regex Headaches with Claude Code
Regular expressions are powerful tools, but complex patterns are hard to read, write, and debug. With Claude Code, you can describe your requirements in natural language and get accurate regex patterns along with test code — all in one go.
If you’re not yet familiar with the basics, start with our Claude Code Getting Started Guide.
Basics: Generating Regex from Natural Language
In your project directory, enter a prompt like this:
> Create a TypeScript regex that matches US phone numbers
> (with and without dashes and parentheses). Include test code.
Example code Claude Code generates:
const phoneRegex = /^(\+1[-\s]?)?(\(\d{3}\)|\d{3})[-\s]?\d{3}[-\s]?\d{4}$/;
// Strict mobile pattern
const mobileRegex = /^(\+1[-\s]?)?\d{3}[-\s]?\d{3}[-\s]?\d{4}$/;
function validatePhone(input: string): boolean {
return phoneRegex.test(input) || mobileRegex.test(input);
}
// Tests
const testCases = [
{ input: "(555) 123-4567", expected: true },
{ input: "555-123-4567", expected: true },
{ input: "+1 555 123 4567", expected: true },
{ input: "5551234567", expected: true },
{ input: "123-456", expected: false },
{ input: "abc-defg-hijk", expected: false },
];
testCases.forEach(({ input, expected }) => {
const result = validatePhone(input);
console.assert(
result === expected,
`Failed: ${input} => ${result}, expected ${expected}`
);
});
console.log("All tests passed!");
Debugging Existing Regular Expressions
When a regex in your project isn’t working correctly, you can ask Claude Code directly.
> Investigate why the emailRegex in src/utils/validator.ts doesn't match [email protected] and fix it
Claude Code reads the file, identifies the issue in the regex, and fixes it. For example, it can instantly catch easy-to-miss bugs like an unescaped + character.
Practical Pattern: Building a URL Parser
Here’s an example of a URL parser useful for web scraping and log analysis.
interface ParsedUrl {
protocol: string;
host: string;
port?: string;
path: string;
query?: Record<string, string>;
fragment?: string;
}
function parseUrl(url: string): ParsedUrl | null {
const regex =
/^(https?):\/\/([^:/?#]+)(?::(\d+))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/;
const match = url.match(regex);
if (!match) return null;
const queryParams: Record<string, string> = {};
if (match[5]) {
match[5].split("&").forEach((pair) => {
const [key, value] = pair.split("=");
queryParams[decodeURIComponent(key)] = decodeURIComponent(value || "");
});
}
return {
protocol: match[1],
host: match[2],
port: match[3],
path: match[4] || "/",
query: match[5] ? queryParams : undefined,
fragment: match[6],
};
}
// Usage
const result = parseUrl("https://example.com:8080/api/users?page=1&limit=10#section");
console.log(result);
// {
// protocol: "https",
// host: "example.com",
// port: "8080",
// path: "/api/users",
// query: { page: "1", limit: "10" },
// fragment: "section"
// }
Improving Regex Readability
When you instruct Claude Code to “use named capture groups,” it generates more readable regular expressions.
// Date parser (using named capture groups)
const dateRegex =
/^(?<year>\d{4})[-\/](?<month>0[1-9]|1[0-2])[-\/](?<day>0[1-9]|[12]\d|3[01])$/;
function parseDate(input: string) {
const match = input.match(dateRegex);
if (!match?.groups) return null;
return {
year: parseInt(match.groups.year),
month: parseInt(match.groups.month),
day: parseInt(match.groups.day),
};
}
console.log(parseDate("2026-04-08"));
// { year: 2026, month: 4, day: 8 }
Prompt Tips
To get more accurate regex generation, include the following in your prompts. For more on effective prompting, see 5 Tips for Better Prompts.
- Provide multiple examples of strings that should match
- Explicitly state strings that should NOT match
- Specify the use case (validation, extraction, replacement)
- Mention language or framework constraints
> Create an email validation regex with the following conditions:
> - Should match: [email protected], [email protected]
> - Should NOT match: @example.com, user@, [email protected]
> - For use in TypeScript. Full RFC 5322 compliance is not required.
Summary
Using Claude Code as a regex assistant dramatically reduces the time needed to create complex patterns. By describing requirements in natural language and generating test cases simultaneously, you improve both the quality and maintainability of your regular expressions.
For more advanced usage, refer to the Claude Code official documentation.
Free PDF: Claude Code Cheatsheet in 5 Minutes
Just enter your email and we'll send you the single-page A4 cheatsheet right away.
We handle your data with care and never send spam.
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
7 Deployment Checks Before You Publish a Multilingual Claude Code Article Every Day
A practical checklist for publishing daily multilingual Claude Code articles without missing locales, breaking CTAs, or shipping stale pages.
Codex Automations for Content Ops: A Daily Revenue Workflow for Claude Code Sites
Use Codex Automations to turn analytics, article updates, CTA improvements, deployment, and verification into a daily revenue workflow.
Claude Code × GCP Cloud Functions Complete Guide | Rapid Serverless Function Development
Streamline GCP Cloud Functions with Claude Code. Implement HTTP/Pub/Sub/Firestore triggers, local testing, and deployment automation with real-world code examples from Masa's experience.
Related Products
50 Battle-Tested Claude Code Prompt Templates
Copy, paste, ship. 50 production-ready prompts.
Use proven prompts for code review, refactoring, testing, documentation, debugging, architecture, and incident response.
The Complete Claude Code Setup & Configuration Guide
From install to team-ready workflow.
A practical guide to installation, CLAUDE.md, hooks, MCP servers, permissions, IDE setup, and CI/CD workflows.