I often use vim / search command to verify my regular expressions (just to see what it matches). After that I usually use the :%s replace command, where I use that regexp from search as a string to be replaced, e.g. I first look for such string:


It matches exactly what I want, so I do my replace:


But I have to write again entire regexp here. Usually that regexp is much longer, that's why I'm looking for solution:

Is there any existing shortcut or vim script for pasting that search pattern directly into replace command?

I use vim in terminal (no gvim).


In general, an empty regular expression means to use the previously entered regular expression, so :%s//\1/g should do what you want.

  • Woah, it's that easy! Exactly what I needed, thanks. – kars7e Mar 12 '11 at 23:49
  • 10
    Also, if you want to verify or modify the last used pattern, you can use Control-r then / to insert the contents of the search pattern register (/) directly into a partially typed command line (e.g. right after :%s/). – Chris Johnsen Mar 13 '11 at 5:10
  • thats very useful hint as well. Thanks @Chris! +1 – kars7e Mar 13 '11 at 10:38
  • What if I want to follow up "\1" with a number like say 23? How do I avoid it being interpreted as "\123"? – Champ Jul 28 '15 at 15:22
  • @Champ As back references only go up to \9, there is no ambiguity. – Kusalananda Aug 25 '17 at 12:47

Another good way to see past regexes searches as well as Ex commands and make changes to them is to edit these commands in normal mode. From this Mode you will have all your vim powers including copy and paste.

  • Searching: rather than ? or / for searching, try q/ or q?
  • for Ex Commands, rather than : try q:
  • to exit this mode use CtrlC

To read more see :help q:.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.