Wikia

Vim Tips Wiki

Simplifying regular expressions using magic and no-magic

Talk0
1,613pages on
this wiki
Revision as of 04:13, May 16, 2012 by JohnBot (Talk | contribs)

Tip 1237 Printable Monobook Previous Next

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 or \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, \m, \M, or \V, to make them immune to the user's 'magic' setting.

The :substitute command has the :smagic and :snomagic alternate forms (the same as \m and \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:

:s/<Ctrl-R>/

References

Comments

Around Wikia's network

Random Wiki