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.


In reply to Re: Highlighting Regex Hits by ikegami
in thread Highlighting Regex Hits by rlrandallx

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.