Atomic groups in regular expressions

Intro
Rarely, but consistently, people using regular expressions meet a scenario where a regular expression becomes incredibly slow. This is called "catastrophic backtracking". There are multiple solutions for this, but the one I am going to be talking today is atomic groups.
Definition
An atomic group has the syntax:
(?>subexpression) . It instructs the regular expression engine that it should greedily match the subexpression and never backtrack. In other words, once it has matched, the engine discards the group's backtracking positions. This leads to a huge performance improvement, but also that if the pattern fails, the engine cannot re-enter the group to try an alternative match.This is also called "non-backtracking subexpression" or "possessive". (possessive quantifiers like
a++ are the same idea).How backtracking works
- Greedy quantifiers take as much as possible, then give characters back on failure.
- Alternation tries branch 1, then branch 2, and so on.
- Each choice point is saved on a stack. Failure pops the stack and retries.
- Cost: failing matches can try every combination (exponential with nested quantifiers).
Examples
| Pattern | Input | Result | Why |
|---|---|---|---|
a+b | aaac | no match, tries 3 lengths of a+ | backtracks |
(?>a+)b | aaac | no match, tries 1 length | no give-back |
a*a | aaa | match | a* gives one a back |
(?>a*)a | aaa | no match | a* is locked |
| ( ?>ab|a)b | ab | no match | alternation locked on ab |
(?:ab|a)b | ab | match | falls back to a |
So atomic can change which strings match, not only speed!
When to use
- Failing matches are cheaper: no retry of equivalent splits
- Guards against catastrophic backtracking (
^(a+)+$onaaaa...!) - Makes it clear the part is decided and should not be revisited
- Often a free optimization when the following token cannot start with the group’s characters (disjoint sets).
When NOT to use
- It changes the result when the group needs to give back text:
(?>a*)a,(?>ab|a)b(?>.*)foonever matches (.*eats everything);.*foodoes- Short inputs: backtracking cost is negligible, atomic adds noise
- Patterns with no ambiguity (no overlapping choices): nothing to prune
- Wrong placement: atomic inside the loop vs around it
- Does not replace a timeout (matchTimeout) or input length limits
- Interpreter overhead: atomic constructs can be slower when they do not prune much
RegexOptions.NonBacktrackingdoes not support atomic groups or lookarounds - choose one approach- Lookaheads and lookbehinds are already atomic in .NET; wrapping them adds nothing.
How to decide
- Does the text matched by this group ever need to be given back for the overall match to succeed? If no, make it atomic.
- Measure with the same regex options used in production (
None,Compiled,NonBacktrackingdiffer a lot). - Benchmark failing inputs, not only matching ones.
- Fuzz old versus new pattern on random short strings from the relevant alphabet.
- Keep the unit tests for allowed, blocked and long inputs.
Alternatives
- Possessive quantifiers (Java, PCRE, not .NET).
- RegexOptions.NonBacktracking (linear time, no atomic groups or lookarounds, set by option rather than pattern).
- RegexOptions.Compiled or source-generated regex (
[GeneratedRegex]). - Match timeout.
- Rewrite for unambiguous alternatives.
- Replace regex with a hand-written scanner.
References
- Microsoft Learn, Grouping constructs (atomic group section): https://learn.microsoft.com/
en-us/dotnet/standard/base- types/grouping-constructs-in- regular-expressions - Microsoft Learn, Backtracking in regular expressions: https://learn.microsoft.com/
en-us/dotnet/standard/base- types/backtracking-in-regular- expressions - Microsoft Learn, Best practices for regular expressions in .NET: https://learn.microsoft.com/
en-us/dotnet/standard/base- types/best-practices-regex - Microsoft Learn, Regular expression options (NonBacktracking): https://learn.microsoft.com/
en-us/dotnet/standard/base- types/regular-expression- options - Regular-Expressions.info, Atomic grouping: https://www.regular-
expressions.info/atomic.html - Regular-Expressions.info, Possessive quantifiers: https://www.regular-
expressions.info/possessive. html - Russ Cox, Regular Expression Matching Can Be Simple And Fast: https://swtch.com/~rsc/regexp/
regexp1.html - Jeffrey Friedl, Mastering Regular Expressions (3rd ed.), chapter on backtracking and efficiency.

Comments
Be the first to post a comment