Search code examples
regexperlsubstitutioncapturing-group

Is it possible to repeat a captured group in the substitution in regular expressions?


Is it possible with regex to repeat a captured group an amount of times with the added restriction that the amount to repeat is also found in a capture group?

Example:

Regex: /(a)([0-9])/g
String: ba1na3na2
Expected result: banaaanaa

I have never seen anything that does this, but maybe I have been looking in the wrong places. Note: I am using Perl - but I am interested to see answers for other flavours as well.


Solution

  • In perl this regular expression will give you the expected result, your regexp is a match, while the s regular expression is a substitution:

    s/(a)([0-9])/$1 x $2/eg;
    

    Like this:

    my $str = 'ba1na3na2';
    $str =~ s/(a)([0-9])/$1 x $2/eg;
    print $str;
    

    banaaanaa

    • The e modifier evaluates the right-hand side as an expression.
    • The x operator repeates the string.

    Update:

    As @AvinashRaj says it might be s/(a)([0-9]+)/$1 x $2/eg; is more approriate. Depending on if you want ba20nana to become

    • baa0nana

    or

    • baaaaaaaaaaaaaaaaaaaanana