Another way, using a positive look-ahead assertion and the \K special escape of 5.10+ (see (?<=pattern) \K in Look Around Assertions) which is effectively a variable-width positive look-behind (an actual look-behind in Perl regex may only be fixed-width):
>perl -wMstrict -le
"my $s =
'there is no FOO stuff i do not want BAR unwanted BAR stuff here';
;;
my $t = $s;
$t =~ s{ FOO \K .*? (?= BAR) }{}xms;
print qq{'$t'};
;;
$t = $s;
$t =~ s{ FOO \K .* (?= BAR) }{}xms;
print qq{'$t'};
"
'there is no FOOBAR unwanted BAR stuff here'
'there is no FOOBAR stuff here'
The given examples illustrate the effect of the ? quantifier modifier to achieve 'lazy' matching. If the substitution is to be done repeatedly, the /g regex modifier should be used.
As suggested above, a positive look-behind could have been used in the examples because the pattern in question is fixed-width, but look-behind assertions, positive or negative, cannot be used for general patterns, which seemed to be the thrust of the OP.
|