Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating replacement pattern number of times in vim

Tags:

regex

vim

I want to do the following in vim.

  • Replace a,2 with a@,a@
  • Replace b,3 with b@,b@,b@
  • Replace c,6 with c@,c@,c@,c@,c@,c@ and so on
like image 935
Rakesh Avatar asked Dec 30 '25 13:12

Rakesh


2 Answers

That's another case for the powerful :help sub-replace-expression:

:%s/\(\w\),\(\d\+\)/\=join(repeat([submatch(1) . '@'], submatch(2)), ',')/g

This matches a word character (\w) followed by , and a number, appends @ to each matched word character (submatch(1) . '@), turns that into a List ([...]), multiplies the List element according to the matched number (repeat()), then join()s that back into a ,-separated string, which is used as the replacement.

This is based on your example; you need to tweak the pattern according to your particular needs.

like image 162
Ingo Karkat Avatar answered Jan 01 '26 09:01

Ingo Karkat


vim has repeat() function. This command should do what you want:

%s/\v([a-z]),(\d+)/\=substitute(repeat(submatch(1).'@,',submatch(2)),',$','','g')/g

Note that this line will change foo,3abc into foo@,o@,o@abc. The result might be not exactly what you are looking for, but by reading the command, you should know the idea, you can change it to make it fit your needs.

like image 43
Kent Avatar answered Jan 01 '26 09:01

Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!