my $text = 'whatever you want in here'; my $n = 10; my $word = 'match'; if ( $text=~ /(([.\s]+\w+){$n}[.\s]+$word[.\s]+(\w+[.\s]+){$n})/ ) { print $1; }