Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to effectively search and replace in Vim by first "testing" or "preview" the search part?

Tags:

regex

replace

vim

Sometimes I want to search and replace in Vim using the s/search_for/replace_with/options format, but the search_for part becomes a complicated regex that I can't get right the first time.

I have set incsearch hlsearch in my .vimrc so Vim will start highlighting as I type when I am searching using the /search_for format. This is useful to first "test"/"preview" my regex. Then once I get the regex I want, I apply to the s/ to search and replace.

But there is two big limitation to this approach:

  1. It's a hassle to copy and paste the regex I created in / mode to s/ mode.
  2. I can't preview with matched groups in regex (ie ( and )) or use the magic mode \v while in /.

So how do you guys on SO try to do complicated regex search and replace in Vim?

like image 537
hobbes3 Avatar asked May 18 '12 03:05

hobbes3


3 Answers

Test your regex in search mode with /, then use s//new_value/. When you pass nothing to the search portion of s, it takes the most recent search.

As @Sam Brink also says, you can use <C-r>/ to paste the contents of the search register, so s/<C-r>//new_value/ works too. This may be more convenient when you have a complicated search expression.

like image 163
Daenyth Avatar answered Oct 13 '22 15:10

Daenyth


As already noted, you can practice the search part with /your-regex-here/. When that is working correctly, you can use s//replacement/ to use the latest search.

Once you've done that once, you can use & to repeat the last s/// command, even if you've done different searches since then. You can also use :&g to do the substitute globally on the current line. And you could use :.,$&g to do the search on all matches between here (.) and the end of the file ($), amongst a legion of other possibilities.

You also, of course, have undo if the operation didn't work as you expected.

like image 6
Jonathan Leffler Avatar answered Oct 13 '22 15:10

Jonathan Leffler


As the others have noted I typically use s//replacement/ to do my replacements but you can also use <C-r>/ to paste what is in the search register. So you can use s/<C-r>//replacement/ where the <C-r>/ will paste your search and you can do any last minute changes you want.

<C-r> inserts the contents of a register where the cursor is
The / register holds the most recent search term
:registers will display the contents of every register so you can see whats available.

like image 5
Sam Brinck Avatar answered Oct 13 '22 16:10

Sam Brinck