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:
/
mode to s/
mode.(
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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With