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

How do I match a pattern only if it is preceded by specific text?

Answer

\@<=pattern

Explanation

The \@<= atom is a positive lookbehind in Vim regex. It matches a pattern only when it is preceded by the specified text, without including the preceding text in the match.

How it works

  • \(text\)\@<=pattern matches pattern only if preceded by text
  • The lookbehind does not consume characters
  • \@<! is the negative version (not preceded by)

Example

Match digits only when preceded by $:

/\$\@<=\d\+

In $100 and 200, this matches 100 but not 200.

Tips

  • \@<= must follow a group: \(pattern\)\@<=
  • Very magic version: /\v(\$)@<=\d+
  • Lookbehinds can be slow with variable-length patterns
  • Use \zs as a simpler alternative when possible

Next

How do you yank a single word into a named register?