MEPX
Chapter 9 of 10All chapters

Chapter 9 of 10

When regex goes wrong

Catastrophic backtracking.

The failure mode

Nested quantifiers over overlapping alternatives can make the engine try an exponential number of paths. A pattern that is fine on short input can hang on a slightly longer one.

  • Patterns like (a+)+b are the classic example.
  • An attacker who controls the input can turn this into a denial of service.

Avoiding it

Keep quantifiers from overlapping, anchor patterns, prefer specific classes over the dot, and set a timeout if your language allows one.