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

How do I replace only part of a match in :substitute without capture groups?

Answer

:%s/\vfoo\zsbar/baz/g

Explanation

When your match has a stable prefix but you only want to replace the trailing segment, \zs is often cleaner than introducing extra capture groups. It resets the start of the effective match at a specific point, so the prefix still constrains where matching happens but is not included in the replacement. This keeps substitutions readable in long patterns and reduces backreference noise.

How it works

  • :%s/.../.../g runs substitution across the whole buffer
  • \v enables "very magic" mode so most regex atoms need less escaping
  • foo\zsbar means: match foo first, then set the start of the replaceable match at bar
  • Because the effective match starts at \zs, only bar is replaced
  • g replaces all occurrences on each line

Example

Input:

foo_bar foo_bar foo_baz

Command:

:%s/\vfoo\zs_bar/-qux/g

Output:

foo-qux foo-qux foo_baz

Notice that foo is required for a match but remains unchanged.

Tips

  • Pair \zs with \ze when you need to isolate a middle segment
  • This pattern scales better than \(foo\)bar when your prefix becomes complex
  • Use c flag (.../gc) for confirmation when refactoring code-like text

Next

How do I keep a utility split from resizing when other windows open or close?