I'm trying to find groups of repeated digits in a number, e.g. 12334555611
becomes (1 2 33 4 555 6 11)
.
This works:
$n.comb(/ 0+ | 1+ | 2+ | 3+ | 4+ | 5+ | 6+ | 7+ | 8+ | 9+ /)
but is not very elegant.
Is there a better way to do this?
I'm trying to find groups of repeated digits in a number, e.g. 12334555611
becomes (1 2 33 4 555 6 11)
.
This works:
$n.comb(/ 0+ | 1+ | 2+ | 3+ | 4+ | 5+ | 6+ | 7+ | 8+ | 9+ /)
but is not very elegant.
Is there a better way to do this?
'12334555611'.comb(/\d+ % <same>/)
Please check the answer of the first task of Perl Weekly Challenge
You may use
$n.comb(/(.) $0*/)
The (.)
creates a capturing group and captures any char into Group 1, then there is a backreference to Group 1 that is $0
in Perl6 regex. The *
quantifier matches zero or more occurrences of the same char as in Group 1.
Replace the .
with \d
to match any digit if you need to only match repeated digits.
See a Perl6 demo online.
In case someone navigates here wanting to remove singleton digits (Raku REPL code below):
m:g
adverb combo):
> put $/ if m:g/ \d**2..* % <same> / given '12334555611';
33 555 11
m:ov
adverb combo):
> put $/ if m:ov/ \d**2..* % <same> / given '12334555611';
33 555 55 11
The difference between the two versions is particularly dramatic as repeated runs get longer:
> given '122333444455555666666' {put $/ if m:g/ \d**2..* % <same> /};
22 333 4444 55555 666666
> given '122333444455555666666' {put $/ if m:ov/ \d**2..* % <same> /};
22 333 33 4444 444 44 55555 5555 555 55 666666 66666 6666 666 66