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

How do I rearrange or transform captured groups in a substitution using Vimscript?

Answer

:s/\(\w\+\) \(\w\+\)/\=submatch(2) . ' ' . submatch(1)/

Explanation

The submatch(N) function lets you access individual capture groups inside a \= (expression replacement) in a substitution. While \1, \2 etc. handle simple backreferences, \=submatch(N) unlocks the full power of Vimscript for transforming matched text.

submatch(0) returns the entire match, and submatch(1), submatch(2), etc. return the text captured by each \(...\) group, making it possible to rearrange, modify, or compute new replacements on the fly.

How it works

  • \(\w\+\) — first capture group: one or more word characters
  • \(\w\+\) — second capture group
  • \= — switch to Vimscript expression mode for the replacement
  • submatch(2) . ' ' . submatch(1) — swap the two groups with a space between them

Example

Given:

John Smith
Jane Doe

After :%s/\(\w\+\) \(\w\+\)/\=submatch(2) . ', ' . submatch(1)/g:

Smith, John
Doe, Jane

Tips

  • Combine with arithmetic: \=submatch(1) + 100 to increment captured numbers
  • Use tolower(submatch(1)) or toupper(submatch(1)) for case transformation
  • Use printf('%05d', str2nr(submatch(1))) to zero-pad captured numbers
  • Unlike \1 backreferences, submatch() can be used in any Vimscript expression, enabling complex transformations impossible with plain regex replacement

Next

How do I highlight all occurrences of a yanked word without typing a search pattern?