vimtricks.wiki Concise Vim tricks, one at a time.

How do I write Vim regex patterns without escaping every special character?

Answer

\v (very magic mode)

Explanation

In Vim's default regex mode, many metacharacters require a backslash: \+ for one-or-more, \(\) for groups, \{\} for quantifiers. Prefix your pattern with \v (very magic mode) and every character that isn't a letter, digit, or underscore automatically becomes a metacharacter — matching PCRE/ERE conventions that most developers already know.

Magic modes

Vim has four magic levels controlled by prefix atoms:

Prefix Mode Metacharacters
\v very magic All non-[a-zA-Z0-9_] chars
\m magic (default) . * [ ] only
\M nomagic Only ^ and $
\V very nomagic No metacharacters (literal search)

Example

Match a function call like foo(bar, 42) using default magic:

/foo(\w\+,\s*\d\+)

With \v very magic:

/\vfoo(\w+,\s*\d+)

Capture groups and back-references also become cleaner:

" default
:\(\w\+\) = \(\w\+\)/\2 = \1
" very magic
:%s/\v(\w+) = (\w+)/\2 = \1/g

Tips

  • Put \v at the start of your search or substitute pattern: /\vpattern or :%s/\vpattern/replacement/g
  • To match a literal special character in \v mode, escape it: \v\(literal parens\)
  • Use \V (very nomagic) when you want to search for a string that contains lots of regex metacharacters and you want all of them treated literally
  • :help magic has the complete table of all magic levels and their effects

Next

How do I run a search and replace only within a visually selected region?