How do I match only part of a search pattern in Vim using \zs and \ze?
Answer
/\(function\s\+\)\zs\w\+
Explanation
Vim's \zs and \ze atoms let you control which part of a matched pattern gets highlighted and operated on. The full regex still needs to match, but only the portion between \zs (start) and \ze (end) is treated as the actual match. This is invaluable for search-and-replace operations where you need context-aware matching without replacing the context itself.
How it works
\zs— Sets the start of the match. Everything before\zsmust match but is excluded from the result.\ze— Sets the end of the match. Everything after\zemust match but is excluded from the result./\(function\s\+\)\zs\w\+— Matches any word that followsfunction, but only the word itself is the match.
Example
Given this code:
function calculateTotal(items)
function validateInput(data)
let result = processData()
Searching with /\(function\s\+\)\zs\w\+ highlights only calculateTotal and validateInput — not the function prefix and not processData (since it is not preceded by function ).
To rename all function names to uppercase:
:%s/\(function\s\+\)\zs\w\+/\U&/g
Tips
- You can use
\zsand\zetogether:/foo\zsbar\zebazmatches onlybarin the stringfoobarbaz. - These atoms work with all Vim search commands including
/,?,:s,:g, and:v. - Think of
\zsas "match starts here" and\zeas "match ends here" — the surrounding pattern is a lookaround.