in reply to 1000000th question about regex lol
Don't know if you're still interested in this, but here's a split-based version. Don't know if it's faster/slower/etc. Didn't know how you would want a zero-length (empty) search string handled, so I special-cased it. Tested with all the previously posted test cases and more. Works with pre-5.10 Perl versions.
sub replace_split_1 { # pre-5.10 safe: no // operator, no regex exten +sions my ($string, # string to search/replace $srch, # search string (no regex metacharacters) $repl, # optional: replacement string (default: '') $n, # optional: number of replacements (default: infinit +e) ) = @_; # handle degenerate cases. return '' unless defined $string; return $string unless defined $srch && length $srch; # ??? # default replacement string: empty string. $repl = '' unless defined $repl; # avoid // (defined-or) operator # replace right-to-left if n is defined and < 0. my $replace_right_to_left = defined($n) && $n < 0; # split limit: one more than absolute of replacement count # unless count is undefined/infinite. my $limit = defined $n ? 1+abs($n) : -1; # split limit # reverse all strings if replacing right-to-left. if ($replace_right_to_left) { $_ = reverse for $string, $srch, $repl; } # split on meta-quoted search substring to specified limit. my @groups = split "\Q$srch", $string, $limit; # replace all instances of search substring. $string = join $repl, @groups; # return result with reversal reversed if needed. return $replace_right_to_left ? reverse $string : $string; } # end sub replace_split_1()
Give a man a fish: <%-{-{-{-<
|
|---|