I'm trying to write a replacement command that would search for a text containing at least 4 letters separated by spaces and remove the spaces:



L i g ht



as expected because a group contains only the last match which was g in that case. How to accumulate all the matches of group \1 and then join them?

1 Answer 1


Given a repeated group like (...){n,m} or (...)+, I don't think there's any way in to Vim extract each occurrence of the group. Only the last is made available in all regex-related functions and commands.

That said, you can use a nested substitution:

:s/\v%([a-zA-Z]\s){3,}[a-zA-Z]/\=substitute(submatch(0), '\s', '', 'g')/gc

A \= in the replacement of :s makes Vim evaluate the replacement as an expression. And in that expression, I'm using the substitute() function to remove all spaces in the entire matched text of :s (obtained by submatch(0)), giving Ligh from L i g h.

  • Thanks. I also thought about removal of spaces in the whole match as a workaround but still hoped it were possible to join all the matches of a group... Please, append 'gc' at the end. I also wanted to confirm the replacement. That was crucial.
    – ka3ak
    May 25, 2018 at 10:15
  • 3
    @ka3ak done. There's also a Vi and Vim Stack Exchange for Vim, if you're interested
    – muru
    May 25, 2018 at 10:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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