Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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)

((?:\[.*?\]){1,4})

(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!
    cheers
    ........
    Those are my principles. If you don't like them I have others.
    -- Groucho Marx
    .......

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2018-10-18 02:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When I need money for a bigger acquisition, I usually ...














    Results (99 votes). Check out past polls.

    Notices?