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

How do I match only part of a search pattern for highlighting or substitution?

Answer

/\zs and \ze

Explanation

The \zs and \ze atoms let you define where the actual match starts and ends within a larger pattern. The surrounding context is used for matching but only the portion between \zs and \ze is highlighted or affected by substitution.

How it works

  • \zs sets the start of the match (everything before it is context, not part of the match)
  • \ze sets the end of the match (everything after it is context, not part of the match)
  • These are far more readable than capture groups for simple substitutions

Example

To change the value in color: red to blue without touching color: :

:%s/color: \zsred/blue/g

This matches lines containing color: red but only replaces red — the color: part is required context but not part of the substitution.

Another example — add quotes around values after =:

:%s/= \zs\w\+\ze/"&"/g

Turns name = hello into name = "hello".

Tips

  • Use \zs alone when you only need to anchor the start: /foo\zsbar highlights only bar in foobar
  • Simpler than capture groups: no need for \( and \) with \1 back-references
  • Works with both / search and :s substitute commands

Next

How do I return to normal mode from absolutely any mode in Vim?