Wednesday, July 29, 2009

Vim Non-Greedy Search

Just a self-post here to help serve as a reminder that the non-greedy search operator for vim is .\{-} instead of the .*? in most languages. This was useful when attempting to replace bad image paths for a template file that contained lots of images that were hosted on various servers and I wanted to consolidate them to get around security warnings. The search command string in vim then ends up as:
:/src=\".\{-}\.\(gif\|png\|jpg\)\"/
This can be combined with a search and replace command as:
:%s/src=\".*\(\/.\{-}\.\(gif\|png\|jpg\)\)\"/src=\"myimagelocation\1\"/gc
Oh, and a super nice thing to know is that you can copy and paste from the cmd line in vim by hitting ctrl-f to open a new cmd window. This is great for saving thost extremely wordy vim regexes that you need to type over and over.