Remove everything except regex match in Vim

This effect can be accomplished by using sub-replace-special substitution and setreg() linewise

:let @a=""
:%s//\=setreg('A', submatch(0), 'l')/g
:%d _
:pu a
:0d _

or all in one line as such:

:let @a=""|%s//\=setreg('A', submatch(0), 'l')/g|%d _|pu a|0d _

Overview: Using a substitution to append each match into register “a” linewise then replace the entire buffer with the contents of register “a”

Explanation:

  1. let @a="" empty the “a” register that we will be appending into
  2. %s//\=setreg('A', submatch(0), 'l')/g substitute globally using the last pattern
  3. the \=expr will replace the pattern with the contents of the expression
  4. submatch(0) get the entire string of what just matched
  5. setreg('A', submatch(0), 'l') append (note: the capital “a”) to @a the matched string, but linewise
  6. %d _ delete every line into the black hole register (aka @_)
  7. pu a put the contents of @a into the buffer
  8. 0d _ delete the first line

Concerns:

  • This will trash one of your registers. This example trashed @a
  • Uses the last search pattern. Although you can modify the substitute command with whatever pattern you want: %s/<pattern>/\=setreg('A', submatch(0), 'l')/g

For more help

:h :s\=
:h :let-@
:h submatch()
:h setreg()
:h :d
:h :p

Leave a Comment