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

How do I search and replace text containing special characters?

Answer

:%s/\V literal.text/replacement/g

Explanation

The \V (very nomagic) flag treats all characters as literal except for \. This is perfect when searching for strings that contain regex special characters.

How it works

  • \V at the start of the pattern disables all magic
  • Only \ has special meaning
  • ., *, [, ], ^, $ are all treated literally

Example

To replace obj.method() with obj.newMethod():

:%s/\Vobj.method()/obj.newMethod()/g

Without \V, the . would match any character and () would need escaping.

Tips

  • \V is the safest mode for literal text replacement
  • In the replacement part, & and \ are still special
  • For the replacement, use \= for expressions
  • You can also escape characters individually: \. for a literal dot

Next

How do you yank a single word into a named register?