in reply to Regex Subexpressions

To start, I assume the regex you meant was

/(a(bc?)?)/g

because yours as posted doesn't match 'ab', though it does match 'ac'. Forgive me if I'm misinterpreting. I came up with what's below, but I'm not at all sure it works in the general case. You can play with it. It gives your desired output, using my regex. It saves a possible match, then fails the regex on purpose to start backtracking to get all the possible matches.

use strict; use warnings; my $test = 'abc'; my @matches; $test =~ /(a(bc?)?)(??{push @matches, $^N})(?!)/; print "@matches\n";
If you can generate the regexes, it would probably be easier just to generate separate regexes.

Replies are listed 'Best First'.
Re^2: Regex Subexpressions
by liverpole (Monsignor) on Sep 09, 2005 at 23:24 UTC
    To produce the output which BenjiSmith is looking for, I would make one modification, s/push/unshift/:
    #!/usr/bin/perl -w use strict; use warnings; my $test = 'abc'; my @matches; $test =~ /(a(bc?)?)(??{unshift @matches, $^N})(?!)/; print "@matches\n";
    Here's another "solution", which may not be at all correct (it matches an input string of "aaa", for example), but does it shed any more light on what the solution should be?:
    #!/usr/bin/perl -w use strict; use warnings; my $test = "abc"; my $count = 1; while ($test =~ m/([abc]{$count})/) { my $match = $1; ++$count; printf "%s\n", $match; }