my $text = "This is a test for the word blue more things blue and then some very large text with a lot of things blue and done"; #### my $WANT = "blue"; my @results = $text =~ m/(?:\w+\s+){0,5} (?:$WANT) (?:\s+\w+){0,5} /xgi; #### a test for the word blue more things blue and then with a lot of things blue and done #### a test for the word blue more things blue and then some very large with a lot of things blue and done #### my $WANT = "blue"; my @results = $text =~ m/(?:\w+\s+){0,5} (?:$WANT) (?:\s+\w+){0,5} (?: \s+(?:$WANT) (?:\s+\w+){0,5} )? /xgi;