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
\zssets the start of the match (everything before it is context, not part of the match)\zesets 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
\zsalone when you only need to anchor the start:/foo\zsbarhighlights onlybarinfoobar - Simpler than capture groups: no need for
\(and\)with\1back-references - Works with both
/search and:ssubstitute commands