Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Regex - backreferencing multiple matches in one group.

by clinton (Priest)
on Mar 04, 2008 at 11:36 UTC ( #671848=note: print w/ replies, xml ) Need Help??


in reply to Regex - backreferencing multiple matches in one group.

Your captures will always be numbered according to the leftmost opening parenthesis, for instance:

'abcdef' =~ / ( abc ( def) ) /x; $1 -> 'abcdef' $2 -> 'def'

So you have two options here. You can either specify each matching group, or match in a loop. For instance:

use Data::Dumper; my $table_ref="!Frequency[A][B][C] ..some other text.."; ### Groups specified explicitly my $var_rx = qr / \[ ( [^\]]+ ) \] /x; my $file_rx = qr / ! ( [^\[]+ ) /x; my $regex = qr/^ $file_rx $var_rx $var_rx? $var_rx? $var_rx? \s ++.*/x; my @matches = ( $table_ref =~ /$regex/); print Dumper (\@matches); ## Loop my ($filename) = ($table_ref =~ /^ $file_rx /gcx ); my @vars; while ( $table_ref =~ /\G $var_rx/gcx ) { push @vars,$1; } print Dumper($filename,\@vars);

See perlre for an explanation of \G and /c

clint


Comment on Re: Regex - backreferencing multiple matches in one group.
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2015-07-06 07:55 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 (70 votes), past polls