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

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/\ze are Vim's equivalent of PCRE look-behind/look-ahead, but much easier to write
  • They work in :s substitutions — only the \zs...\ze portion gets replaced
  • You can use \zs without \ze and vice versa
  • These are extremely useful in syntax highlighting definitions (syn match) to highlight precisely

Next

How do I run a search and replace only within a visually selected region?