#! /usr/bin/env perl use 5.014; use warnings; # We're going to try matching substrings of this... my $MASTER_STR = 'abcdabcdabceabcdabcdabceab'; # Using this pattern to find (possibly truncated) repetitions... my $REPETITION_PAT = qr{ \A # Start at the beginning of the string (.+?) # Match minimal initial sequence (as $1) (?{$^N}) # Remember it internally (as $^R) (?| # Then either it's not truncated... \1+ # Rematch it exactly as often as possible \z # ...until the end of the string () # Remember that nothing was left over (as $2) | # Or else it is truncated... \1* # Rematch it exactly as often as possible (or not) (.+) # Then grab what's left (as $2)(internally as $^N) \z # ...until the end of the string # Then verify that what's left is a proper truncation... (??{ # If what's left ($^N) is substring of repetition ($^R)... $^N eq substr($^R,0,length($^N)) ? q{} # ...then do nothing (i.e. keep matching) : q{(?!)} # ...else initiate backtracking }) ) }xms; # Loop through increasingly truncated substrings... for my $substr (1..length($MASTER_STR)) { # Compute the substring... my $str = substr($MASTER_STR,0,-$substr); # Evaluate the match... if ($str =~ $REPETITION_PAT) { say "$str\n Matched: $1*$2"; } else { say "$str\n Didn't match"; } }