my $WANT = "blue"; my @results = $text =~ m/(?:\w+\s+){0,5} (?:$WANT) (?:\s+\w+){0,5} (?: \s+(?:$WANT) (?:\s+\w+){0,5} )? /xgi;