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

How do I match a pattern but only highlight or capture part of it using \zs and \ze?

Answer

\zs and \ze

Explanation

How it works

Vim's \zs (set start) and \ze (set end) atoms let you define which portion of a pattern counts as the actual match, even though the full pattern is used for searching. Everything before \zs and after \ze provides context but is not part of the match itself.

  • \zs marks where the match starts
  • \ze marks where the match ends

This is similar to lookahead and lookbehind assertions but with a simpler syntax.

Example

Find numbers that appear after price: but only match the number itself:

/price: \zs\d\+

Given the text price: 42, the entire pattern matches but only 42 is highlighted and counted as the match. The price: part is required context but not part of the result.

This is extremely powerful in substitute commands. To change only the value after a key:

:%s/timeout: \zs\d\+/300/g

This finds lines like timeout: 60 and replaces just the number with 300, resulting in timeout: 300. Without \zs, you would need capture groups: :%s/\(timeout: \)\d\+/\1300/g.

You can use both together to match a substring within a larger context:

/src="\zs[^"]*\ze"

This matches the URL inside src="https://example.com" -- only https://example.com is the match, not the surrounding quotes.

Combining \zs and \ze with substitute makes targeted replacements much cleaner than using capture groups, and the patterns are easier to read.

Next

How do you yank a single word into a named register?