Avoid the need to escape parenthesis, brackets… in vim regexes

Sat, 2009-01-17

Vim has a so called “very magic” mode for regexes which allows you to use parenthesis, brackets, the alternative separator (i.e. ‘|’), pluses, etc. with their special meaning but without the need to escape those characters.

(see :help /\v)

Example:

Let’s say you have the following in your buffer:

12345aaa678
12345bbb678
12345aac678

If you execute

:%s/\d\{5\}\(\D\+\)\d\{3\}/\1/

you will get

aaa
bbb
aac

but it required a lot of backslash escaping in the regex. You can avoid the need to escape parenthesis, curly braces, pluses, etc. using vim’s “very magic” mode for regexes. The following would do exactly the same as the previous substitution command but with fewer escaping required:

:%s/\v\d{5}(\D+)\d{3}/\1/