title: Remove everything except regex match in Vim
body: <p>My specific case is a text document that contains lots of text and IPv4 addresses. I want to remove everything except for the IP addresses.</p>
  
  <p>I can use <code>:vglobal</code> to search for <code>([0-9]{1,3}\.){3}[0-9]{1,3}</code> and remove all lines without IP addresses, but after that I only know how to search for the whole line and select the matching text. Is there an easier way.</p>
  
  <p>In short, I'm looking for a way to do the following without using an external program (like grep):</p>
  
  <pre><code>grep --extended-regexp --only-matching --regexp="([0-9]{1,3}\.){3}[0-9]{1,3}"
  </code></pre>
  
  <p>Calling grep from vim may require adapting my regex (ex: removing \v). Using vim's incremental search shows me that I've got the pattern right, and I don't want to verify my regex in grep too.</p>
  
  <hr>
  
  <p><strong>Edit:</strong> Thanks to Peter, here's the function I now use. (C is the register I generally clobber in my functions.)</p>
  
  <pre><code>"" Remove all text except what matches the current search result
  "" The opposite of :%s///g (which clears all instances of the current search).
  function! ClearAllButMatches()
      let old = @c
      let @c=""
      %s//\=setreg('C', submatch(0), 'l')/g
      %d _
      put c
      0d _
      let @c = old
  endfunction
  </code></pre>
  
  <p><strong>Edit2:</strong> I made it a command that accepts ranges (but defaults to whole file).</p>
  
  <pre><code>"" Remove all text except what matches the current search result. Will put each
  "" match on its own line. This is the opposite of :%s///g (which clears all
  "" instances of the current search).
  function! s:ClearAllButMatches() range
      let is_whole_file = a:firstline == 1 &amp;&amp; a:lastline == line('$')
  
      let old_c = @c
  
      let @c=""
      exec a:firstline .','. a:lastline .'sub//\=setreg("C", submatch(0), "l")/g'
      exec a:firstline .','. a:lastline .'delete _'
      put! c
  
      "" I actually want the above to replace the whole selection with c, but I'll
      "" settle for removing the blank line that's left when deleting the file
      "" contents.
      if is_whole_file
          $delete _
      endif
  
      let @c = old_c
  endfunction
  command! -range=% ClearAllButMatches &lt;line1&gt;,&lt;line2&gt;call s:ClearAllButMatches()
  </code></pre>