How do I load yanked text into search as a literal pattern without regex escaping headaches?
Answer
:let @/='\V'.escape(@", '\\')
Explanation
When you yank text that contains regex characters like ., *, [, or (, pasting it directly into / search can produce unexpected matches. :let @/='\V'.escape(@", '\\') loads the unnamed register into the search register as a literal pattern, so Vim searches the exact text instead of treating it as regex syntax.
How it works
@/is Vim's search register (the pattern used byn,N,*repeats, and substitute defaults).'\V'enables very nomagic mode for the pattern, making nearly everything literal.escape(@", '\\')escapes backslashes from the yanked text so they remain literal under\V.:letassigns the final pattern directly, avoiding manual escaping in the command line.
This is powerful during code review and refactors when you need to find an exact snippet copied from logs, JSON, regex-heavy strings, or generated code. It keeps search precise and reduces false positives from accidental regex interpretation.
Example
You yank this text:
user.id == order.items[0].id
Run:
:let @/='\V'.escape(@", '\\')
Then press n to jump to the next exact occurrence of that full string.
Tips
- Combine with
cgnto perform exact-match iterative replacements safely. - Use the same trick with any register, e.g.
@ainstead of@". - Preview the final pattern via
:echo @/before searching large files.