How do I match only part of a search pattern in Vim using \zs and \ze?
Answer
/\vfoo\zsbar\ze/
Explanation
Vim's \zs (start of match) and \ze (end of match) atoms let you control which portion of a pattern is treated as the actual match. The full pattern is still used to locate text, but only the part between \zs and \ze is highlighted or affected by substitutions. This is invaluable for complex search-and-replace operations where you need context anchoring without replacing the context itself.
How it works
\zs— Sets the start of the match. Everything before it is required for the pattern to match, but is not included in the match result.\ze— Sets the end of the match. Everything after it is required for the pattern to match, but is not included in the match result.\v— Enables "very magic" mode so you don't need to escape most special characters.
You can use either atom alone or both together.
Example
Suppose you want to replace bar only when it follows foo:
:%s/\vfoo\zsbar/baz/g
Before:
foobar foobaz somebar
After:
foobaz foobaz somebar
Only the bar in foobar is replaced — somebar is untouched because it lacks the foo prefix.
Tips
- Use
\zeto anchor the end:/\vfoo\zebarhighlights onlyfoowhen followed bybar. - These atoms are similar to lookahead/lookbehind in other regex flavors but are more intuitive for substitution.
- Combine with
\zsin substitutions to avoid capture groups entirely — cleaner than\(\)with back-references.