How do I search for a pattern but only highlight or operate on part of the match?
Answer
\zs and \ze
Explanation
The atoms \zs (set match start) and \ze (set match end) let you define a sub-match boundary inside a larger pattern. Everything before \zs and after \ze is required to match but is excluded from the actual match result. This means highlights, substitutions, and operations only affect the bounded portion.
How it works
\zs— the actual match starts here (everything before is a look-behind)\ze— the actual match ends here (everything after is a look-ahead)- The surrounding context must still match, but it is not included in the result
Examples
Highlight only the value after key=:
/key=\zs\w\+
Matches value in key=value — the key= part is required but not highlighted.
Replace only the number in port: 8080:
:%s/port: \zs\d\+/3000/g
Changes port: 8080 to port: 3000 without touching port: .
Match a word only if followed by a comma:
/\w\+\ze,
Highlights the word but not the comma.
Combine both:
/foo\zs.*\zebar
Matches everything between foo and bar, excluding foo and bar themselves.
Tips
\zs/\zeare Vim's equivalent of PCRE look-behind/look-ahead, but much easier to write- They work in
:ssubstitutions — only the\zs...\zeportion gets replaced - You can use
\zswithout\zeand vice versa - These are extremely useful in syntax highlighting definitions (
syn match) to highlight precisely