Search code examples
regexvimquoting

How to make Vim not require backslashes before regex control characters


The number of slashes one must use in Vim regexes is very, very unfortunate:

:%s/\(\w\+\)\(.*\s\+\)\(\w\+\)$/\3\2\1/

Is there any way to reverse the rules so that I can write

:%s/(\w+)(.*\s+)(\w+)$/\3\2\1/

And I would only have to quote (, ), ., *, +, etc. if I want them to match that literal character?


Solution

  • What you refer to is called "very magic" mode (see :help magic).

    You can switch it on for an expression with the \v flag:

    :%s/\v(\w+)(.*\s+)(\w+)$/\3\2\1/
    

    By default this is not enabled and it's not a good idea at all to enable it by default. But you can always use it in a per-expression manner.

    There are two different magic modes, switched on by \v and \m, and switched off by \V, \M respectively. Just like case-sensitivity via \c and \C, you can use those flags to make only a part of the expression magic.

    But if you switch it on at the start of the expression and don't switch it off again, the entire expression is seen as magic.