<<

NAME

Koha::Regex::Replacement - expand a regular-expression replacement string as data

SYNOPSIS

    use Koha::Regex::Replacement;

    if ( $value =~ /$search/ ) {
        my $text = Koha::Regex::Replacement::expand_template(
            $replacement,      # the user-supplied replacement string
            [ @{^CAPTURE} ],   # numbered capture groups from the match ($1 is element 0)
            { %+ },            # named capture groups from the match
        );
    }

DESCRIPTION

Koha lets staff run regular-expression find and replace over MARC fields, item fields and call numbers. The replacement half of those substitutions used to be run through Perl's s///ee, which evaluated the replacement as Perl code and so allowed arbitrary code execution (see bug 30233).

Note: It was necessary to use s///ee because Perl does not provide a native way of processing backreferences and backslash escapes in the replacement string at runtime. While this doesn't matter when running hard-coded regular expressions, it does make it difficult to support replacement strings provided by end users.

Note: While the "expand_template" may seem bespoke, it works similarly to how Python's own template expansion works in Python's re.sub() regular expression substitution function: https://github.com/python/cpython/blob/3.15/Modules/_sre/sre.c#L3022

This module expands the replacement string as data instead of evaluating it. It walks the string once, from left to right, and only acts on the handful of placeholders a replacement legitimately contains:

Every other character is copied through unchanged. Because the string is never evaluated, interpolation blocks such as @{[ ... ]} and ${ ... } end up in the output as ordinary text rather than being run as Perl.

Case-folding escapes (\U, \L, \u, \l, \E) are deliberately left out. They are a display nicety rather than a requirement, and omitting them keeps this routine small and easy to follow. They can be added later if a real call-number or MARC workflow turns out to need them.

FUNCTIONS

expand_template

    my $text = Koha::Regex::Replacement::expand_template( $replacement, \@captures, \%named_captures );

Returns $replacement with the placeholders listed above resolved. Numbered backreferences are looked up in \@captures (element 0 is group 1, matching @{^CAPTURE}) and named captures in \%named_captures (matching %+). A reference to a group that did not match, or to a name that is not present, expands to the empty string. The input is treated purely as data and is never run as code.

<<