HeoLab
ToolsBlogAboutContact
HeoLab

Free developer tools with AI enhancement. Built for developers who ship.

Tools

  • JSON Formatter
  • JWT Decoder
  • Base64 Encoder
  • Timestamp Converter
  • Regex Tester
  • All Tools →

Resources

  • Blog
  • What is JSON?
  • JWT Deep Dive
  • Base64 Explained

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Service

© 2026 HeoLab. All rights reserved.

Tools work in your browser. Zero data retention.

HomeBlogHow to Write Efficient Regular Expressions
Table of Contents▾
  • Table of Contents
  • What is Catastrophic Backtracking?
  • The Evil Regex
  • Practical Optimization Rules
  • When Not to Use Regex
deep-dives#regex#performance#optimization

How to Write Efficient Regular Expressions

Regex can be slow — learn how to avoid catastrophic backtracking, optimize your patterns, and use the right tools for the job.

Trong Ngo
February 22, 2026
2 min read

Table of Contents

  • What is Catastrophic Backtracking?
  • The Evil Regex
  • Practical Optimization Rules
  • When Not to Use Regex

What is Catastrophic Backtracking?

A poorly written regex can take exponential time to fail on a non-matching input. This is known as ReDoS (Regular Expression Denial of Service), and it's been responsible for outages at Cloudflare and Stack Overflow.

The Evil Regex

/^(a+)+$/

On input aaaaaaaaaaaab, the engine tries every possible grouping before concluding no match. The patterns (X+)+, (X|X)+, and (X+)* are red flags.

// Can take seconds or cause a timeout:
/^(a+)+$/.test("aaaaaaaaaaaaaaaaaab");

Practical Optimization Rules

1. Be specific — avoid over-using .*

// Slow
/<.*>/

// Fast — negated class
/<[^>]*>/

2. Anchor when possible

// Scans the whole string
/\d+/

// Anchored — stops early
/^\d+$/

3. Use non-capturing groups

// Capturing group (slower)
/(\d+)/

// Non-capturing group (faster)
/(?:\d+)/

4. Most likely alternatives first

/\.(?:jpg|png|gif|webp)$/i

When Not to Use Regex

  • Parsing HTML/XML: Use a DOM parser
  • Parsing JSON: Use JSON.parse()
  • Complex validation: Use a dedicated validator library

Test your patterns safely with the Regex Tester.

Try These Tools

Regex Tester & Debugger

Test regular expressions against strings in real-time. Visualize matches, groups, and flags.

Related Articles

Mastering Regex Lookahead and Lookbehind

2 min read

Using Regex for Form Validation: Patterns and Pitfalls

2 min read

10 Regex Patterns Every Developer Should Know

1 min read

Back to Blog

Table of Contents

  • Table of Contents
  • What is Catastrophic Backtracking?
  • The Evil Regex
  • Practical Optimization Rules
  • When Not to Use Regex

Related Articles

Mastering Regex Lookahead and Lookbehind

2 min read

Using Regex for Form Validation: Patterns and Pitfalls

2 min read

10 Regex Patterns Every Developer Should Know

1 min read