Dear Monks,

This is a regex question so forgive me if I should be asking it somewhere else.

Here's my problem: I am searching thru a string/document for a word. If I find it, I wish to print the line no., line and highlight the word (square brackets is ok but I would really like ANSI color.) The issue is when there is more than one hit on the same line. I've read all about global matching but nothing works. Below is my code:

: $line = 'This line has a hit here and a hit there."; $word = 'hit'; $count = 0; while ($line =~ /\b$word\b/gi )#I also tried "/gic" & pos() { $line = "$`".'['."$&".']'."$'"; $count++ } print "$lino $line\n"; : print "$word was found $count times\n";

With color, the one line is "$line = "$`".BLACK \ ON_YELLOW ."$&".RESET."$'"; Anyway, if I replace the 'while' with an 'if' it highlights the first 'hit'. I just can't get the other(s) to highlight. I know it is because I an modifying $line but this structure has worked before so I am trying to find an alternate "sure-fire" way.

Thanks for any help -rlrandallx

In reply to 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.