in reply to Can I get some help with a regex please
The only reason I can imagine for using substitution in a situation like this is if the block of text to be changed is a sub-block within a larger text block:
(The \Q...\E metaquoting (update: of the interpolated $sub_str string) is necessary so that newlines are matched literally when the /x modifier is used.)c:\@Work\Perl\monks>perl -wMstrict -le "my $str = qq{cat\nman\ncat\ndog\neel\nman\nman\ncat\ncat\nman\n}; ;; my $sub_str = qq{cat\nman\n}; my $n = 3; ;; $str =~ s{ (\Q$sub_str\E) }{ join '', map qq{$_ $1}, 1 .. $n }xmsge; print qq{>$str<}; " >1 cat man 2 cat man 3 cat man cat dog eel man man cat 1 cat man 2 cat man 3 cat man <
Of course, once you have this structure, it's easy to go to full regex search/replace:
(Update: Note that metaquoting is not needed here because $sub_str is a Regexp object: \n matches a literal newline.)c:\@Work\Perl\monks>perl -wMstrict -le "my $str = qq{cat\nman\ncat\ndog\neel\nman\nman\ncat\ncat\nwoman\n}; ;; my $sub_str = qr{ cat \n (?: wo)? man \n }xms; my $n = 3; ;; $str =~ s{ ($sub_str) }{ join '', map qq{$_ $1}, 1 .. $n }xmsge; print qq{>$str<}; " >1 cat man 2 cat man 3 cat man cat dog eel man man cat 1 cat woman 2 cat woman 3 cat woman <
Give a man a fish: <%-{-{-{-<
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Can I get some help with a regex please
by misterperl (Friar) on Jun 14, 2023 at 14:16 UTC | |
by cavac (Prior) on Jun 14, 2023 at 21:52 UTC |