in reply to Re: Precompiling substitution regex
in thread Precompiling substitution regex

['(robert|bobby)', 'bob']

Your example regex has a capture group, but the subsequent substitution doesn't seem to offer any opportunity to use what was captured. Is there any reason for capturing?

Replies are listed 'Best First'.
Re^3: Precompiling substitution regex
by Anonymous Monk on Jul 02, 2014 at 13:48 UTC
    No, that's a typo. Interesting - is there a way to pass captured groups to be substituted instead of straight strings?

      Okay my stab at using captured groups as well is to use eval in the replacement evaluation, i.e.,

      foreach (@SUB_REC) { $yourText =~ s/$_->[0]/eval qq{"$_->[1]")/eg; }

      The above allows me to pass replacement strings and capture groups, e.g.,

      my @SUB_REC = map {[qr{$_->[0]}, $_->[1]]} ( ['robert|bobby', 'bob'], ['(abc)(1234)(def)', '$1$3'] );

        Using a doubled  /e regex modifier is also possible and, IMHO, better because it is simpler. (The  /e modifier can be repeated any number of times for additional 'levels' of expression evaluation.)

        c:\@Work\Perl>perl -wMstrict -le "my @SUB_REC = map [ qr{$_->[0]}, $_->[1] ], ( [ '\b(robert|bobby)\b', 'bob (not $1)' ], ) ; ;; my $yourText = 'robert dobbs and roberto jones and bobby hope'; print qq{'$yourText'}; ;; $yourText =~ s{ $_->[0] }{ qq{qq{$_->[1]}} }xmsgee for @SUB_REC; print qq{'$yourText'}; " 'robert dobbs and roberto jones and bobby hope' 'bob (not robert) dobbs and roberto jones and bob (not bobby) hope'