in reply to How to color the regex captured groups?
G'day ovedpo15,
I see others have shown you how to access the captured text.
"I came a cross with the Term::ANSIColor module which can help me color the string without writing the color codes myself."
I wasn't sure if you were asking for help using Term::ANSIColor. In case you were, here's a demo. I do recall that I found the documentation difficult to follow when I first used it. By the way, it's a core module: no need to install it.
#!/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; }
Prints:
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"
— Ken
|
|---|