#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11148806 use warnings; my $text = 'This is just an arbitrary example of text.'; #ONLY TWO WORDS ARE CAPTURED--WE WANT TO HIGHLIGHT ONLY THOSE my $query = qr~(?:(?:This)|(?:That)).*?(just).*?(arbitrary).*?$~; #THIS WOULD HIGHLIGHT THE ENTIRE LINE #$text =~ s~($query)~$1~g; $text =~ $query and do { for ( reverse 1 .. $#- ) { substr $text, $+[$_], 0, ''; substr $text, $-[$_], 0, ''; } }; print $text, "\n"; #### This is just an arbitrary example of text.