use strict; use warnings; my $match1 = 'something '; my $fill = 'xxxxxx '; my $match2 = 'somethingelse '; my $nomatch = 'nomatch '; my @targets = ( "$nomatch$fill$match1$match2$nomatch", "$nomatch$fill$match1$fill$match2$nomatch", "$nomatch$fill$match1$fill$nomatch$fill$match2$nomatch", ); for my $test (@targets) { if ($test =~ /$match1 ((?:(?!$nomatch) .)*) $match2/x) { print "Matched >$1< for: $test\n"; } else { print "Failure for $test\n"; } }