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:
- It’s a hassle to copy and paste the regex I created in
/mode tos/mode. - I can’t preview with matched groups in regex (ie
(and)) or use the magic mode\vwhile 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 uses//new_value/. When you pass nothing to the search portion ofs, it takes the most recent search.As @Sam Brink also says, you can use
<C-r>/to paste the contents of the search register, sos/<C-r>//new_value/works too. This may be more convenient when you have a complicated search expression.