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 (highlightspatternwithout a/search):let @/ = @a— use the contents of registeraas the search pattern:let @/ = ""— clear the search highlight programmatically (equivalent to:nohlsearchbut 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
@/triggershlsearchhighlighting 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 hlsearchfor instant visual feedback on programmatic searches