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
    Excellent! I couldn't figure out the "substr" part in the online examples I was seeing, and this particular issue seemed to have an added twist at that. This was what I needed to see. I begin to understand, now, what the "substr" is doing.

    Thank you.

    Blessings,

    ~Polyglot~

      > I couldn't figure out the "substr" part in the online examples

      please note that you can alternatively use the substr function as an lvalue

      substr EXPR,OFFSET,LENGTH = REPLACEMENT

      which should be easier to figure out.

      Cheers Rolf
      (addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
      Wikisyntax for the Monastery