How to match the same number of different atoms in Perl 6 regex?

Viewed 214

Should be very simple, but I can't cope with it.

I want to match exactly the same number of as as bs. So, the following

my $input = 'aaabbbb';
$input ~~ m:ex/ ... /;

should produce:

aaabbb
aabb
ab

UPD: The following variants don't work, perhaps because of the :ex bug , mentioned in @smls's answer (but more likely because I made some mistakes?):

> my $input = "aaabbbb";
> .put for $input ~~ m:ex/ (a) * (b) * <?{ +$0 == +$1 }> /;
Nil
> .put for $input ~~ m:ex/ (a) + (b) + <?{+$0 == +$1}> /;
Nil

This one, with :ov and ?, works:

> my $input = "aaabbbb";
> .put for $input ~~ m:ov/ (a)+ (b)+? <?{+$0 == +$1}> /;
aaabbb
aabb
ab

UPD2: The following solution works with :ex as well, but I had to do it without <?...> assertion.

> $input = 'aaabbbb'
> $input ~~ m:ex/ (a) + (b) + { put $/ if +$0 == +$1 } /;
aaabbb
aabb
ab
2 Answers
my $input = "aaabbbb";
say .Str for $input ~~ m:ov/ (a)+  b ** {+$0} /;

Output:

aaabbb
aabb
ab

It's supposed to work with :ex instead of :ov, too - but Rakudo bug #130711 currently prevents that.

my $input = "aaabbbb";
say .Str for $input ~~ m:ov/ a <~~>?  b  /;

Works with ex too

my $input = "aaabbbb";
say .Str for $input ~~ m:ex/ a <~~>?  b  /;

Upd: explanation

<~~> means call myself recursively see Extensible metasyntax. (It is not yet fully implemented.)

Following (longer, but maybe clearer) example works too:

  my $input = "aaabbbb";
  my token anbn { a <&anbn>? b} 
  say .Str for $input ~~ m:ex/ <&anbn> /;
Related