Saturday, October 26, 2019

Perl : Highlight Matches in String

That is, you have a string, and now, you have a bunch of patterns to match and, you now want to print the string with the matches highlighted. How/why?

Start with why so Simon don't cuss : You can use this to build your own personal search engine. Who needs to contend with the crappiness of Evernote?

How :

use Term::ANSIColor qw(:constants);
have your patterns in @regexes = ( 'string1', '\bword1\b', 'etc')

Then, (this one assumes all the items in @regexses will match. If that's not your data, put in an if :)

foreach $word ( @regexes ){
  $string =~ /^(.*?)($word)(.*?)$/;
  $string = $1 . UNDERLINE . $2 . RESET . $3;
}


Seem amateurish? :)

No comments: