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
\zssets the start of the match (everything before is a zero-width assertion)\zesets 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
\zsand\zeare Vim-specific (not in standard regex)- They replace the need for lookahead/lookbehind in many cases
- Work in
:substituteto replace only the matched portion \@=and\@!provide full lookahead/lookbehind