TutreNews Learn

Regex in practice

Pitfalls, performance and limits

Goal: Avoid catastrophic backtracking and know when not to use a regex · 9 min

Regular expressions are powerful, but three habits keep them safe.

1. Catastrophic backtracking. When a pattern has nested quantifiers over overlapping choices, e.g. (a+)+ or (\w+\s?)*, a failing match can try an exponential number of ways to split the text. A 30-character input can freeze a page or server (a "ReDoS" attack). Signs: (x+)+, (x*)*, (x|x)*. Fix by removing the overlap: a+ instead of (a+)+, or use specific, non-overlapping classes.

2. Do not parse nested structure. HTML, JSON, programming languages and balanced parentheses are not "regular". Use a real parser (JSON.parse, the DOM) instead.

3. Readability. A pattern nobody can read is a bug waiting. Strategies:

  • Build it from named pieces: const day = "(0[1-9]|[12]\\d|3[01])" and combine with new RegExp.
  • Add a comment above the pattern that shows examples.
  • Prefer a simple string method (includes, startsWith, split(",")) when it does the job.
  • Never place user input into a pattern without escaping it first, because user text may contain metacharacters.

Finally: always test with examples that must fail, not only those that pass.

Worked example: Escaping user input

  1. A user searches for "1+1" in a text. The raw pattern /1+1/ means "one or more 1, then 1".
  2. Escape all metacharacters first: s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").
  3. Now "1+1" is found literally.
const esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const text = "2 + 1+1 = 3";
console.log(new RegExp(esc("1+1")).test(text), new RegExp("1+1").test("11"));

Output:

true true