Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining regexes using a loop in Perl 6

Tags:

raku

Here I make a regex manually from Regex elements of an array.

my Regex @reg =
  / foo /,
  / bar /,
  / baz /,
  / pun /
  ;

my $r0 = @reg[0];
my $r1 = @reg[1];

my Regex $r = / 0 $r0 | 1 $r1 /;

"0foo_1barz" ~~ m:g/<$r>/;
say $/;  # (「0foo」 「1bar」)

How to do it with for @reg {...}?

like image 969
Eugene Barsky Avatar asked Feb 15 '26 00:02

Eugene Barsky


1 Answers

If a variable contains a regex, you can use it without further ado inside another regex.

The second trick is to use an array variable inside a regex, which is equivalent to the disjunction of the array elements:

my @reg =
  /foo/,
  /bar/,
  /baz/,
  /pun/
  ;

my @transformed = @reg.kv.map(-> $i, $rx { rx/ $i $rx /});

my @match =  "0foo_1barz" ~~ m:g/ @transformed /;

.say for @match;
like image 74
moritz Avatar answered Feb 19 '26 15:02

moritz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!