in reply to Highlighting Regex Hits

It is possible to achieve using m//g.

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";

/c would indeed allow you to simplify the above.

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/sgci) { $hilit .= "$1[$2]"; ++$count; } $hilit .= substr($line, pos($line)); print "$hilit\n"; print "$count occurrences of $word\n";

But s///g is much simpler.

my $line = 'This line has a hit here and a hit there.'; my $word = 'hit'; my $count = (my $hilit = $line) =~ s/\b($word)\b/[$1]/gi; print "$hilit\n"; print "$count occurrences of $word\n";

Note that if $word can contain characters other than those matched by \w, \b may fail and the contents may be treated as a regex instructions (e.g. $word="foo.bar" would match foolbar).

Update: Fixed a bug in first snippet.

Replies are listed 'Best First'.
Re^2: Highlighting Regex Hits
by rlrandallx (Initiate) on May 15, 2010 at 02:42 UTC
    OK now. Can anyone get it to work with ANSI COLORS? -rlrandallx
        I got it working! Thanks for your help! -rlrandallx