Storing a search string in VIM?

Viewed 191

I have a fairly elaborate regex string for finding IP addresses (25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{1,2}. etc.) If, for instance, I want to get all instances of the IP address, I have to delete everything in the line prior to the instance, and in a second call, I have to delete everything after the instance. Is there a way that I could store the search string as a variable to use in multiple replacements?

For instance:

    Store the string in register "a"
:y a 25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{1,2}\. . .
    Refer back to register "a" when deleting everything before the address
:%s/^.*(\a)/\1/g
    And again when deleting everything after it
:%s/(\a).*$/\1/g

BTW, I know you can delete before and after the parenthetical. I'm just using that as an example.

2 Answers

You can use Ctrl-R to insert the contents of a register into the command line. From :help c_CTRL-R:

CTRL-R {0-9a-z"%#:-=.}                                  c_CTRL-R c_<C-R>
            Insert the contents of a numbered or named register.  Between
            typing CTRL-R and the second character '"' will be displayed
            to indicate that you are expected to enter the name of a
            register.

There's also a related Ctrl-RCtrl-R command that may work better if you have certain unusual characters in your register.

My TaggedSearchPattern plugin can add a special neutral label to the search pattern itself, so that it can be easily identified in the search history (:help q/), and it also has mappings to just view the tagged searches. With this, you don't need to store the pattern in a separate Vim variable, as 8bittree's answer suggests.

Related