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
\venables very magic mode, so the pattern is less backslash-heavyfoois left context that must be present\zsmarks where the real match startsbaris the part Vim treats as the match\zemarks where the real match endsbazis 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.
\zsand\zealso work in:globaland:substitutepatterns.