Friday, October 01, 2010

Vim Trick : Search and Replace

Today I found out a cool vim trick. Not so much great, but sure it's nice to know.

For example, if you want to search for string consisting of all a's followed by all b's and then reverse it.

aaaaaabbb -> bbbaaaaaa


\(regexp\) defines an atom in vim. So the first atom is defined as a* and the second is defined as b*. In the replace pattern we are executing a vim expression. submatch(0) stands for the entire matched pattern where as submatch(1), submatch(2) stands for the strings matched by first atom, second atom etc.

So the above vim command reverses the order of a's and b's. Having a vim expression as a replace pattern gives enormous power and can be used for much more complex things :-)

No comments: