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

How do I make Vim match only part of a larger regex using \zs and \ze?

Answer

/\vfoo\zsbar\zebaz

Explanation

When you need to target only a slice of a larger pattern, \zs and \ze are usually cleaner than building lookarounds. They let Vim match the full context but treat only the middle portion as the actual match. This is especially useful for precise substitutions where surrounding text must remain unchanged.

How it works

  • \v enables very magic mode, so the pattern is less backslash-heavy
  • foo is left context that must be present
  • \zs marks where the real match starts
  • bar is the part Vim treats as the match
  • \ze marks where the real match ends
  • baz is right context that must also be present

Only bar is considered matched, even though foo and baz must exist around it.

Example

Given this text:

fooBARbaz
foo123baz
fooXYZbaz

Search with:

/\vfoo\zs\u+\zebaz

Vim matches only BAR and XYZ (the uppercase segment), not the full foo...baz span.

Tips

  • Combine with substitute to edit only the inner segment while anchoring on stable context.
  • Prefer this over complicated lookbehind/lookahead when portability and readability matter.
  • \zs and \ze also work in :global and :substitute patterns.

Next

How do I convert all hexadecimal numbers to decimal in Vim?