nak3c nak3c - 3 months ago 28
Perl Question

perl non-greedy matching

ultra simple question here about non-greedy matching; given:

my $seq = "TTATGCTTCTTATGCCCACACACACCCACTCACCCATT";


want to match: TTATGCCCACACACACCCACTCACCCATT non greedily

tried the following:

my ($hit) = $seq =~ m/(TTATG.*?CCATT)/;
($hit) = $seq =~ m/(TTATG(.*)?CCATT)/;
($hit) = $seq =~ m/(TTATG.+?CCATT)/;


but $hit is always assigned to the entire string. What am I missing?

Answer

Frugal (aka non-greedy or lazy) means "shortest", but still "leftmost". You need look-around assertions to find the other matches:

 while ($seq =~ m/(?=(TTATG.*?CCATT))/g) {
    say for $seq, $1;
}