in reply to How to color the regex captured groups?

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11146126 use warnings; # Given path: /a/b/c/d # Given regex: ^/a/b/([^/]*)/([^\/]*) # Output: /a/b/\033[1;31mc\033[0m/\033[1;31md\033[0m my ($boldred, $reset) = ( "\e[1;31m", "\e[0m" ); my $string = '/a/b/c/d/'; my $regex = qr{^/a/b/([^/]*)/([^\/]*)/}; $string =~ $regex or die "no match of $string by $regex"; my $coloredstring = $string; my $count = @- - 1; for ( reverse 1 .. $count ) { substr $coloredstring, $+[$_], 0, $reset; substr $coloredstring, $-[$_], 0, $boldred; } print "$coloredstring\n"; use Data::Dump 'dd'; dd 'coloredstring', $coloredstring;

Outputs:

/a/b/c/d/ ("coloredstring", "/a/b/\e[1;31mc\e[0m/\e[1;31md\e[0m/")