in reply to substitution in regular expression

If you just want to extract overlapping triplets without changing the original string:

c:\@Work\Perl\monks>perl -wMstrict -le "my $s = 'ABCDEF'; ;; my @triplets = $s =~ m{ (?= (...)) }xmsg; printf qq{'$_' } for @triplets; " 'ABC' 'BCD' 'CDE' 'DEF'

If you want to simultaneously do substitutions to change the match string so that it ends up as 'DEF' or 'EF', that's trickier (at least, it's tricky to do with a single substitution operation), but I'm assuming substitution is just an artifact of the potential approach you happened to come up with, i.e., it's an XY Problem. Please advise on this point.

Update: See Re^3: substitution in regular expression for a string-modifying  s/// solution.

Replies are listed 'Best First'.
Re^2: substitution in regular expression
by aeqr (Novice) on Apr 23, 2014 at 20:06 UTC
    Thanks for the help, it's ok to modify the string. I would like to do it in the way I described if it's possible.

      Maybe (?) something like this is what you want?

      c:\@Work\Perl\monks>perl -wMstrict -le "my $s = 'ABCDEF'; ;; my @triplets; $s =~ s{ (?= (...)) . }{ push @triplets, $1; ''; }xmsge; ;; print qq{'$s'}; printf qq{'$_' } for @triplets; " 'EF' 'ABC' 'BCD' 'CDE' 'DEF'

      Update: Here's another  s/// solution. I'm not sure I like it so much: I'm always suspicious, perhaps without cause, of code embedded in a regex. In addition, the  @triplets array must be a package global (ideally local-ized) due to a bug in lexical management that wasn't fixed until Perl version 5.16 or 5.18 (I think — I don't have access to these versions and I'm too lazy to check the on-line docs).

      c:\@Work\Perl\monks>perl -wMstrict -le "my $s = 'ABCDEF'; ;; local our @triplets; $s =~ s{ (?= (...) (?{ push @triplets, $^N })) . }''xmsg; ;; print qq{'$s'}; printf qq{'$_' } for @triplets; " 'EF' 'ABC' 'BCD' 'CDE' 'DEF'

      So how should the string end up, as 'DEF' or as 'EF'?

        Well it doesn't matter as long as the dictionary contains DEF in the last entry.