created 2006 · complexity basic · author Peter Hodge · version 6.0
If you love regular expressions, you probably like to use them everywhere. Unfortunately it gets very confusing when you use Vim's regular expressions, Perl and POSIX compliant varieties in PHP, and then command-line grep as well, because they all seem to have different rules as to which characters have special meaning on their own and which do not. Quite often I need several attempts to write a search pattern because I can't remember which characters need to be preceded by a backslash.
Thankfully, any Vim search pattern can include the special sequence
\v (very magic), and this will make every following character except a-zA-Z0-9 and '_' have special meaning. Using
\V has the opposite effect: all characters have their literal meaning and must be preceded by
\ to activate their special meaning. So if you have forgotten which characters have special meaning in Vim, start the pattern with
\V to switch them all on or off.
Vim's default 'magic' setting makes characters have the same meaning as in grep, and
\v (very magic) makes them the same as the extended regular expressions used by egrep.
Regular expressions in scripts should always specify one of
\V, to make them immune to the user's
:substitute command has the
:snomagic alternate forms (the same as
\M), so you can search and replace with
%sno/regex/new_text/g. Alternatively, you might find it helpful to refine your regular expression by searching with
/\v first, then you can insert your regular expression by typing:
Permanent "very magic" mode
Vim does not have an option to use "very magic" by default (whereas
:set ignorecase will always ignore case unless
\C is used). The following mappings, however, effectively achieve the same purpose (from stackoverflow):
nnoremap / /\v vnoremap / /\v cnoremap %s/ %smagic/ cnoremap \>s/ \>smagic/ nnoremap :g/ :g/\v nnoremap :g// :g//
This does not work with `:g` and interferes somewhat with Vim's search-history behavior (see the StackOverflow link). An alternative solution is to use this plugin: http://www.vim.org/scripts/script.php?script_id=4849