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

How do I access and manipulate the last search pattern as a register?

Answer

"/

Explanation

Vim stores the last search pattern in the special / register. Like any named register, you can read it, paste it, and even write to it — which silently sets the current search highlight without adding to the search history.

How it works

  • "/p — paste the last search pattern as text
  • <C-r>/ — insert the last search pattern in command-line or insert mode
  • :let @/ = "pattern" — set the search register (highlights pattern without a / search)
  • :let @/ = @a — use the contents of register a as the search pattern
  • :let @/ = "" — clear the search highlight programmatically (equivalent to :nohlsearch but persistent)

Example

You searched for \v(foo|bar) and now want to use it in a substitution on a different range:

:let @/
" Shows: '\v(foo|bar)'
:1,10s//replacement/g
" Reuses the last search pattern for the range 1-10

Or copy a word into the search register to highlight it without navigating away:

:let @/ = expand('<cword>')

Tips

  • Writing to @/ triggers hlsearch highlighting immediately without moving the cursor
  • This is useful in Vimscript functions to set up a highlight without side-effects
  • The / register is read-only when accessed via <C-r>/ but fully writable via :let @/ = ...
  • Combine with set hlsearch for instant visual feedback on programmatic searches

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?