Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Regex - backreferencing multiple matches in one group.

by moritz (Cardinal)
on Mar 04, 2008 at 11:18 UTC ( #671845=note: print w/replies, xml ) Need Help??

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

Two ways:

1) (recommended) parse all indexes in one group, and then postprocess it (for example with split)


(capturing parenthesis on the outside)

2) "fancy": Use the experimental (?{ ... }) code assertions (but be sure to read the warnings in perlre first):

my @indexes; my $re = qr{ ... # everything before (?: \[ # opening [ ([^\]]+) # everthing except ] \] # closing ] (?{ push @indexes, $^R}) # store the match )+ # as many times as you want }x

Update: here's why your solution doesn't work:

The variables $1, $2, ... are set up at the time the pattern is compiled (ie before the regex engine sees the string it will match on).

It counts the opening parenthesis from left to right, binding the first one to $1, the second to $2 etc.

So you get this mapping:

re: (..) (..)+ vars: $1 $2

Now each time the second group matches, it writes the captured string into $2, which means you'll get the last match of that group in $2.

Replies are listed 'Best First'.
Re^2: Regex - backreferencing multiple matches in one group.
by wade (Pilgrim) on Mar 04, 2008 at 17:15 UTC
    So, this is either non-responsive (since I'm not using regexes) or one of those "hey, I never thought of that" situations. A cheater approach to this problem is to use 'split':
    use strict; use warnings; my $input = "!Frequency[A][B][C] ..some other text.."; $input =~ s/^!//; # dump that leading '!' print "'$input'\n"; my @pieces = split(/[\]\[]+/, $input); foreach my $piece (@pieces) { print "PIECE '$piece'\n"; }
Re^2: Regex - backreferencing multiple matches in one group.
by why_bird (Pilgrim) on Mar 04, 2008 at 11:56 UTC
    I see, thankyou :) Just deciding whether to play around with the 'fancy' option---I probably will, then decide to use the simple one anyway!
    Those are my principles. If you don't like them I have others.
    -- Groucho Marx

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://671845]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2018-07-18 20:26 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (395 votes). Check out past polls.