Home > other >  How to replace something with n duplicates of itself with regex?
How to replace something with n duplicates of itself with regex?

Time:11-02

I am using Sublime Text.

I want to replace Hi with 30 of itself, so I captured (Hi) in the find field, and entered $1{30} in the replace field. This didn't work. What is the proper syntax to do this?

I can't find the answer through Google, even though it seems very basic.

CodePudding user response:

There is no backreference multiplication operators in replacement patterns, nor can you use limiting quantifiers (that are regex pattern constructs, not replacement pattern constructs) like you did to achieve that result.

The only proper "plain regex" way is to repeat $1 thirty times.

In programming languages though, there are occastions when you can pass the match object to a callback function, where you can already use string manipulation provided by the programming language, e.g. in Python:

import re
text = "Hi, Friend!"
print( re.sub(r'Hi', lambda z: z.group() * 30, text) )
# => HiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHiHi, Friend!
  • Related