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

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/

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: