I'm trying to copy just the matches in my regex search to a register in VIM on windows.

That said, I found the following script for doing this:

function! CopyMatches(reg)
  let hits = []
  %s//\=len(add(hits, submatch(0))) ? submatch(0) : ''/ge
  let reg = empty(a:reg) ? '+' : a:reg
  execute 'let @'.reg.' = join(hits, "\n") . "\n"'
command! -register CopyMatches call CopyMatches(<q-reg>)

However, when I run the script and try to paste my matches from register a, it comes back blank. Is there something else that I need to do to make this work?

  • 2
    Works for me. Did you run a search before running :CopyMatches a?
    – muru
    Apr 15, 2016 at 19:44

1 Answer 1


Note this line:

%s//\=len(add(hits, submatch(0))) ? submatch(0) : ''/ge

The search pattern is empty, which means it will re-use that last pattern that was used. So, this command relies on you having run /foo before running this command.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.