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

How do I match a pattern only if it is followed by another pattern?

Answer

/pattern\ze followed

Explanation

The \ze atom marks the end of the match, so you can match a pattern only when it appears before specific text. Similarly, \zs marks the start of the match.

How it works

  • \zs sets the start of the match (everything before is a zero-width assertion)
  • \ze sets the end of the match (everything after is a zero-width assertion)
  • These let you control exactly what gets highlighted and captured

Example

To match foo only when followed by bar:

/foo\ze bar

This highlights only foo but requires bar to follow.

To match the number after line :

/line \zs[0-9]\+

This highlights only the number, not the word line.

Tips

  • \zs and \ze are Vim-specific (not in standard regex)
  • They replace the need for lookahead/lookbehind in many cases
  • Work in :substitute to replace only the matched portion
  • \@= and \@! provide full lookahead/lookbehind

Next

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