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

How do I search only a sub-part of a larger pattern using \zs and \ze?

Answer

/foo\zsbar\zebaz<CR>

Explanation

Sometimes you need Vim to match a long structural pattern but only treat one piece of it as the actual match. \zs and \ze solve this cleanly: they redefine where the match starts and ends without changing the surrounding context checks. This is especially useful in advanced search-and-replace workflows where you want precise targeting without capturing groups and backreference noise.

How it works

  • / starts a forward search
  • foo is required context before the real target
  • \zs sets the start of the reported match at this point
  • bar is the part Vim treats as the match
  • \ze sets the end of the reported match
  • baz is required trailing context after the match

Vim still requires the whole foobarbaz structure, but only bar is considered the matched text.

Example

Given:

foobarbaz
fooquxbaz
foobaz

Search with:

/foo\zsbar\zebaz

Only the bar inside foobarbaz is matched. The other lines are skipped because they do not satisfy both required contexts.

Tips

  • \zs and \ze work with :substitute, so you can replace just the inner segment while anchoring on rich context.
  • Prefer this over broad groups when you want concise patterns that are easier to read during iterative edits.

Next

How do I enable matchit so % jumps between if/else/end style pairs?