use warnings; use strict; # Min and max length for each pattern my $min = 2; my $max = 8; # Number of patterns my $num = shift; # Generate pattern to capture words my $words = join ('', map { "(.{$min,$max})" . "(?:" . join( '|', map("\\$_", 1..$_)) . ")*" } 1..$num); $_="bookhelloworldhellohellohihellohiworldhihelloworldhihellobookpenbookpenworld"; if (my @pats = /^$words$/) { for my $pat (@pats) { print "[$pat]\n"; } } stan:~/tmp >./tst 5 [book] [hello] [world] [hi] [pen]