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

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 \zs must match but is excluded from the result.
  • \ze — Sets the end of the match. Everything after \ze must match but is excluded from the result.
  • /\(function\s\+\)\zs\w\+ — Matches any word that follows function , 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 \zs and \ze together: /foo\zsbar\zebaz matches only bar in the string foobarbaz.
  • These atoms work with all Vim search commands including /, ?, :s, :g, and :v.
  • Think of \zs as "match starts here" and \ze as "match ends here" — the surrounding pattern is a lookaround.

Next

How do I return to normal mode from absolutely any mode in Vim?