in reply to How to do regex backreferences within $variable replacement text?

Finally got a moment away from child minding :). Here's a non-eval technique:

use warnings; use strict; my $udStr = "abcabcabc"; my $udSearch = '(a)'; my $udRep = '---$1---'; print "before: $udStr\n"; my $before = $udStr; $udStr =~ s/$udSearch/$udRep/; my @starts = @-; my @ends = @+; for (1..$#starts) { my $replace = substr $before, $starts[$_], $ends[$_] - $starts[$_]; $udStr =~ s/\$$_(?=\D)/$replace/; } print "after: $udStr\n";

Prints:

before: abcabcabc after: ---a---bcabcabc

This still doesn't fix (?{...}) and (??{...}) in $user_defined_search, but those could be filtered.


Perl is Huffman encoded by design.

Replies are listed 'Best First'.
Re^2: How to do regex backreferences within $variable replacement text?
by Hue-Bond (Priest) on Sep 18, 2005 at 01:26 UTC

    One can also add a 'g' to lines 10 and 17 to replace all ocurrences of $udSearch.

    --
    David Serrano

      Yes, I intended to :(. Must be in Sunday mode.


      Perl is Huffman encoded by design.
Re^2: How to do regex backreferences within $variable replacement text?
by Hue-Bond (Priest) on Sep 18, 2005 at 02:20 UTC

    Before seeing your code, I had tried something similar but limited only to $1. Now I've worked on it a bit more and came up with this. Just another WTDI.

    use warnings; use strict; my $user_defined_string = "There's more than one way to do it (more th +an one)."; my $user_defined_search = '(more)(.*?)(one)'; my $user_defined_replace = '<b>$1</b>$2<b>$3</b>'; my (@subs) = $user_defined_string =~ /$user_defined_search/; for my $sub (1..@subs) { $user_defined_replace =~ s/\$$sub/$subs[$sub-1]/ge; } print "mangled replace: $user_defined_replace\n"; $user_defined_string =~ s/$user_defined_search/$user_defined_replace/g +e; print "after: $user_defined_string\n"; __OUTPUT__ mangled replace: <b>more</b> than <b>one</b> after: There's <b>more</b> than <b>one</b> way to do it (<b>more</b> t +han <b>one</b>).

    As we can see, the user is expected to have a deep understanding of Perl regexes (non-greediness in this example) if she wants to do fancy stuff ;^).

    --
    David Serrano

      This simply does not work!

      Replace the search text with "There's more than one way to do it (more or less than one)." and you'll see what I mean.

      you don't do any backreferencing but a simple replacement with the first strings found.

      $\=~s;s*.*;q^|D9JYJ^^qq^\//\\\///^;ex;print