Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Retrieving Regex matched Group name

by Kenosis (Priest)
on Feb 18, 2013 at 23:11 UTC ( #1019411=note: print w/ replies, xml ) Need Help??


in reply to Retrieving Regex matched Group name

If I'm understanding you correctly, it seems that you are attempting to use named capture groups and, if there's a match, retrieve the name of the matching group. If so, consider the following:

use strict; use warnings; my $string = 'word_one word_one word_two 2000 word_three 3000'; while ( $string =~ m/(?<Word>\w+)\s+(?<Digit>\w+)/g ) { my %groupNames; push @{ $groupNames{ $+{$_} } }, $_ for keys %+; print "Match : $1 GroupName(s): @{ $groupNames{$1} }\n"; }

Output:

Match : word_one GroupName(s): Word Digit Match : word_two GroupName(s): Word Match : word_three GroupName(s): Word

Group names and their associated values are contained in the hash %+. The above creates a hash of arrays (HoA) keyed on the (captured) values of %+, since two different keys may have identical values. The @{ $groupNames{$1} } notation uses the captured match as a key, and its associated value is the list of capture group names.

Hope this helps!


Comment on Re: Retrieving Regex matched Group name
Select or Download Code
Replies are listed 'Best First'.
Re^2: Retrieving Regex matched Group name
by Samman_Mahmoud (Initiate) on Feb 19, 2013 at 21:23 UTC
    ThanK U Kenosis that's exactly what I was Looking for :)

      You're most welcome, Samman_Mahmoud!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2015-07-08 02:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls