Categories
Coding

Useful Vim Regular Expression

I just edited a patch file and needed to change the paths of the patch directories (why do some patch implementations use relative paths, and others use absolute)? Anyway, I wanted to change all paths like ./src/main/org/apache to be ./src/main/java/org/apache and all test class paths to be ./src/test/org/apache to be ./src/test/java/org/apache. Anyways, it occured to me that if we make the assumption that all test classes will have *Test* somewhere in the name, we can construct positive and negative lookahead regexes in Vim, as follows:

Negative Lookahead (change all paths that dont contain “Test”):
:%s/\(src\/main\)\(.*Test\)\@!/src\/main\/java/g

Positive Lookahead (change all paths that do contain “Test”):
:%s/\(src\/test\)\(.*Test\)\@=/src\/test\/java/g

Very handy! The only slight annoyance is that Vim doesnt go with Perl’s more readable lookaround syntax.