In VIM, using search and replace like :%s/pat/repl/g, is it possible to have a quantifier in the replace part? As an example, replace every line matching pat by exactly 100 # without actually typing exactly 100 #'s into the command? Something like


which, however, doesn't work for me.

More generally, is it possible to replace matches by a captured amount of characters? For example replace

This 3 is a text 5 
with some 2 numbers.


This XXX is a text XXXXX 
with some XX numbers.

using something like :%s/\(\d\)/X\{\1}/g?

1 Answer 1


You are searching for "sub-replace-expression":

:%s/\(\d\)/\=repeat('X', submatch(1))/g

With \= the replace string is a Vim script expression. Here the function repeat() is called. This functions returns a String that repeats the given String count times. The String is X and the count is the first match group.

See :help sub-replace-expression and :help repeat().

  • Thank you, this is exactly what I was looking for!
    – Kilroy
    Commented Mar 22, 2019 at 12:40

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.