tags:

views:

119

answers:

4

Is there an easy way to save a commonly used Regex pattern so that I can reuse it between different files? I look through many log files and always need create a mildly complex regex (it's not rocket science but it is a pain to retype) to find errors so it would be good to have a way to recall that without having to save it in a text file and paste it into the search params each time.

+1  A: 

Just press / and then arrow up.

Or create commands to invoke regexp search.

:command -nargs=0 Errors vimgrep "Error\s*regexp" % | cw 15

and then just

:Errors
Mykola Golubyev
+1  A: 

If you've started typing a command in vim, including a search or a replace, pressing 'up' should search in your history for recently used commands with the same prefix.

Andrew Aylett
+3  A: 

There are a couple of ways:

  • Create a mapping that does what you want and add it to your .vimrc, e.g: map /foo /[long complicated regex]. But beware that this will make it hard to search for the literal string "foo", though it can be done with Ctrl-V escapes. Another way is to use some other prefix for your custom regex searches, e.g. map ::foo /[complicated regex].
  • Create a function that does the regex search that you want and add it to your .vimrc.
  • Some combination of the above
JSBangs
+3  A: 

Put:

source ~/.regexlist.vim

into your vimrc.

Do the search. Decide you might want to use that one again. Type this literally:

:sp ~/.regexlist.vim<CR>
olet MyRegExName = '<C-R>/'<ESC>
:w<CR>
:so %<CR>
:q<CR>

Where <C-R> is CtrlR, <CR> is ENTER and <ESC> is ESC.

Next time you want to use it:

/<C-R>=MyRegExName<CR><CR>

Ctrl-R is your friend! Ctrl-R followed by / pulls up the last search. Ctrl-R followed by = allows you to enter an expression.

Al