Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: How to color the regex captured groups?

by kcott (Archbishop)
on Aug 13, 2022 at 05:15 UTC ( [id://11146136]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11146136]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-23 22:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found