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

How do I force magic regex mode for one substitute command in Vim?

Answer

:smagic/\vfoo.+/bar/

Explanation

If you prefer very-magic regex syntax but don't want to change global settings, :smagic is a targeted solution. It applies 'magic' behavior for a single substitute command, then leaves the rest of your session untouched. This is useful when you need a dense regex once, but still want your normal substitute habits afterward.

How it works

  • :smagic runs a substitute with magic mode enabled
  • /\vfoo.+/ is the search pattern (here using \v very magic syntax)
  • /bar/ is the replacement

Because this is command-scoped, you avoid toggling options like set magic globally or re-escaping patterns when switching contexts.

Example

Given:

foo123
fooABC
zzz

Run:

:smagic/\vfoo.+/bar/

Result:

bar
bar
zzz

Only lines matching the regex are replaced, and magic handling applies only to this one command.

Tips

  • Use :snomagic for the opposite behavior when you want mostly literal matching.
  • Add flags as usual, for example :smagic/\vfoo.+/bar/gc for global+confirm.
  • Keep :smagic in mind when working with copied regexes from other tools where escaping differs.

Next

How do I convert all hexadecimal numbers to decimal in Vim?