vimtricks.wiki Concise Vim tricks, one at a time.

How do I use an atomic group in a Vim regex to prevent backtracking?

Answer

\@>

Explanation

Vim's \@> syntax creates an atomic group in a regular expression. Once a subpattern enclosed in \(...\)\@> matches, the regex engine commits to that match and will not backtrack into the group even if the overall match later fails. This enables possessive-quantifier semantics and can prevent catastrophic backtracking in complex patterns.

How it works

Place \@> immediately after a \(grouping\) to make it atomic:

  • \(pattern\)\@> — the group matches once and locks in; no retries allowed
  • If the rest of the regex fails, the engine cannot revisit the atomic group to try a shorter or different match
  • In very magic mode (\v), the syntax becomes (pattern)@>

Example

To match a sequence of word characters that is not followed by a digit, using an atomic group to prevent the engine from shrinking the word match:

/\(\w\+\)\@>\d\@!

Without \@>, the engine could backtrack \w\+ to try leaving the final character for \d\@! to match differently. The atomic group prevents that.

Tips

  • Combine with \@! (negative lookahead) to build possessive-quantifier patterns: \(pattern\)\@>\(other\)\@!
  • Useful when patterns like \(...\)* with nested quantifiers risk catastrophic backtracking on long inputs
  • Very magic equivalent: /\v(pattern)@>
  • See :help /\@> for the full specification

Next

How do I make Vim's indent commands always align to a clean shiftwidth boundary?