Reputation: 30218
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?
Upvotes: 10
Views: 1959
Reputation: 2366
Since Neovim 0.1.7 there is the Incremental (“live”) :substitute function. (so this only works in Neovim!)
To enable it set the incommand option:
:set inccommand=split
It was announced here: https://neovim.io/news/2016/11/
Upvotes: 3
Reputation: 901
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.
Upvotes: 5
Reputation: 37441
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.
Upvotes: 16
Reputation: 753695
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.
Upvotes: 6