my $line = 'This line has a hit here and a hit there.'; my $word = 'hit'; my $count = 0; my $hilit = ''; while ($line =~ /(.*?)(?:\b($word)\b|\z)/sgi) { $hilit .= $1; if (defined($2)) { ++$count; $hilit .= "[$2]"; } } print "$hilit\n"; print "$count occurrences of $word\n";