Adding text before and after a regular expression match in Vim

Let say that you have a series of lines of text that you want to convert into 'System.out.println' or 'printf' statements, for example:

1 myapplication - an application that does something
2 usage: myapplication [-abch] param1 param2
3   -a: does a particular feature
4   -b: does another feature
5   -c: does yet another feature
6   -h: shows this help message

It’s is laborious to append all those print statements manually, so the generally you’ll want to use regular expressions to replace it for you. One way of doing this with POSIX compliant regular expression with grouping:

:'<,'>s/\(.*\)/printf("\1");/

(Note that this assumes that you have selected the given block with the ‘v’ keystroke or from the mouse already. Subsequent examples will also assume the same.)

Vim requires escapes for the parenthesises, by which one of the ways of shortening it may be by using the '\v' (very magic) operator:

:'<,'>s/\v(.*)/printf("\1");/

But the shortest way so far that I’ve found in vim is to use the '\&' matching operator, which works even when grouping is not explicitly used:

:'<,'>s/.*/printf("\&");/

The resultant output should for the quoted example is shown below, if you are too lazy to try it and see for yourself:

1 printf("myapplication - an application that does something");
2 printf("usage: myapplication [-abch] param1 param2");
3 printf("  -a: does a particular feature");
4 printf("  -b: does another feature");
5 printf("  -c: does yet another feature");
6 printf("  -h: shows this help message");

It’s certainly much more powerful to be able to perform replacements like that with pinpoint accuracy at a single go, something that ‘search and replace’ text editors that do not have regular expressions capabilities are able to do.

If you like reading this, you may also enjoy: