Performance regex

2 snippets in Regular Expressions

Also written as regex performance

RXRegular Expressions

Atomic Groups (Concept)

RX · Advanced Techniques
syntax
(?>pattern)   (PCRE/Java; not native in JS or Python re)
example
PCRE:  (?>\d+)\s matches '123 ' but NOT by backtracking into digits
Python (regex module):
  import regex
  regex.search(r'(?>\d+):', '123:')
output
Matches '123:' -- once the digits are consumed, the engine cannot give them back

Note Atomic groups discard all backtracking positions once the group matches. They are a performance optimization to prevent catastrophic backtracking. In Python, use the third-party 'regex' module. In JS, there is no direct equivalent -- simulate with a possessive quantifier mindset or restructure the pattern.

Catastrophic Backtracking

RX · Common Mistakes
syntax
Dangerous: (a+)+$  or  (.*a){10}  or  (x+x+)+y
example
JS:  // DANGER: This can freeze your browser/server!
     // /(a+)+$/.test('aaaaaaaaaaaaaaaaaaaaaaaaaab')
     // The engine tries exponential combinations before failing
Py:  # Same risk: re.search(r'(a+)+$', 'aaa...ab')
output
Extremely slow or hangs -- exponential backtracking

Note Catastrophic backtracking occurs when the regex engine explores an exponential number of paths. It happens with nested quantifiers applied to overlapping patterns. Prevention: avoid nested quantifiers on similar character sets, use atomic groups or possessive quantifiers, add anchors, or restructure the pattern. This is one of the most common causes of regex-based DoS (ReDoS) vulnerabilities.