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

How do I match only part of a search pattern in Vim using \zs and \ze?

Answer

/pattern\zs.*\ze/

Explanation

Vim's \zs (start of match) and \ze (end of match) atoms let you define a search pattern but only highlight or operate on a portion of it. This is extremely useful for substitutions where you want to match context without replacing it.

How it works

  • \zs — sets the start of the actual match to the current position in the pattern
  • \ze — sets the end of the actual match to the current position
  • Everything before \zs and after \ze is matched but not included in the match result

For example, /foo\zsbar matches "bar" only when preceded by "foo". The cursor lands on "bar" and only "bar" is highlighted.

Example

Suppose you want to replace the value inside quotes after name=:

name="old_value"
name="another_old"

Using:

:%s/name="\zs[^"]*\ze"/new_value/g

Result:

name="new_value"
name="new_value"

The name=" and closing " serve as context anchors but are preserved — only the text between them is replaced.

Tips

  • Combine \zs/\ze with \v (very magic) mode for cleaner regex: /\vname\="\zs[^"]*\ze"
  • These atoms eliminate the need for capture groups in many substitution patterns
  • Works with all search-based commands: /, ?, :s, :g, and n/N

Next

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