#!/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)~<span class="highlight">$1</span>~g; $text =~ $query and do { for ( reverse 1 .. $#- ) { substr $text, $+[$_], 0, '</span>'; substr $text, $-[$_], 0, '<span class="highlight">'; } }; print $text, "\n";
Outputs:
This is <span class="highlight">just</span> an <span class="highlight" +>arbitrary</span> example of text.
In reply to Re: Highlighting only captured groups from larger regex
by tybalt89
in thread Highlighting only captured groups from larger regex
by Polyglot
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |