use strict; my $string = 'ri\d+'; while (my $line = <>) { if ($line =~ m{ (?: \Q$string\E ){3} }xms) { print $line; } }