wrinkles has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks,
Movable Type has a "regex_replace" tag modifier that takes two arguments, a regular expression, and a replacement expression, and returns the modified string.
My problem is that I'd like to write a plugin that returns an array of the individual modified strings instead of the whole string. I thought that would be easy. And it may be, but not for me. The challenge is that while the match regex operator can return an array, the same is not true for substitutions. So while the following returns matches, the behaviour is not the same for substitutions.
@matches = $text =~ /$regex/smg)Here's the original code for MT's "regex_replace" modifier. I'd offer my attempts, but really I tried a lot of things and just got nowhere. I end up just getting the number of substitutions whereas I'd like to capture the substitutions themselves.
TIA!
(update: corrected title spelling)=head2 regex_replace Applies a regular expression operation on the input. This filter accep +ts B<two> input values: one is the pattern, the second is the replacement +. B<Example:> <$mt:EntryTitle regex_replace="/\s*\[.+?\]\s*$/",""$> This would strip any bracketed phrase from the end of the entry title field. =cut sub _fltr_regex_replace { my ( $str, $val, $ctx ) = @_; # This one requires an array return $str unless ref($val) eq 'ARRAY'; my $patt = $val->[0]; my $replace = $val->[1]; if ( $patt =~ m!^(/)(.+)\1([A-Za-z]+)?$! ) { $patt = $2; my $global; if ( my $opt = $3 ) { $global = 1 if $opt =~ m/g/; $opt =~ s/[ge]+//g; $patt = "(?$opt)" . $patt; } my $re = eval {qr/$patt/}; if ( defined $re ) { $replace =~ s!\\\\(\d+)!\$1!g; # for php, \\1 is how you +write $1 $replace =~ s!/!\\/!g; eval '$str =~ s/$re/' . $replace . '/' . ( $global ? 'g' : + '' ); if ($@) { return $ctx->error("Invalid regular expression: $@"); } } } return $str; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: capture global substituion inot an array
by moritz (Cardinal) on Apr 29, 2012 at 16:37 UTC | |
by wrinkles (Pilgrim) on Apr 29, 2012 at 17:39 UTC | |
by ww (Archbishop) on Apr 29, 2012 at 17:45 UTC | |
by wrinkles (Pilgrim) on Apr 29, 2012 at 17:50 UTC | |
by wrinkles (Pilgrim) on Apr 30, 2012 at 17:52 UTC |