#!/usr/bin/env perl use strict; use warnings; use Term::ANSIColor; my $path = '/a/b/c/d'; my $re = qr{^/a/b/([^/]*)/([^\/]*)}; my $demo_fmt = '%-28s : '; printf $demo_fmt, 'Input - plain text from OP'; print "$path\n"; if (my @matches = $path =~ /$re/) { my $debug_path = $path; for (reverse 1 .. $#-) { substr $debug_path, $-[$_], $+[$_] - $-[$_], colored($matches[$_ - 1], 'red'); } printf $demo_fmt, 'Output - "c" & "d" are red'; print "$debug_path\n"; printf $demo_fmt, 'Output - internals of string'; use Data::Dump; dd $debug_path; } #### Input - plain text from OP : /a/b/c/d Output - "c" & "d" are red : /a/b/c/d Output - internals of string : "/a/b/\e[31mc\e[0m/\e[31md\e[0m"