in reply to Highlighting only captured groups from larger regex
#!/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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Highlighting only captured groups from larger regex
by Polyglot (Chaplain) on Dec 13, 2022 at 02:17 UTC | |
by LanX (Saint) on Dec 13, 2022 at 12:29 UTC |