how to interpolate string containing capture-group parentheses as regex in Raku?

You could do the following to expose the inner regex result to an outside variable:

my $rx = "(.*)a(.*)b(.*)";
my $result;

'xaybz' ~~ / $<result>=<$rx> {$result = $<result>}/;

say $result;

# OUTPUT:

# 「xaybz」
# 0 => 「x」
# 1 => 「y」
# 2 => 「z」

The problem is that things in <…> don't capture in general.

'xaybz' ~~ / <:Ll> <:Ll> <:Ll> /
# 「xay」

They do capture if the first thing after < is an alphabetic.

my regex foo { (.*)a(.*)b(.*) }

'xaybz' ~~ / <foo> /;
# 「xaybza」
#  foo => 「xaybza」
#   0 => 「x」
#   1 => 「y」
#   2 => 「za」

That also applies if you use <a=…>

'xaybz' ~~ / <rx=$rx> /;
# 「xaybza」
#  rx => 「xaybza」
#   0 => 「x」
#   1 => 「y」
#   2 => 「za」

Of course you can assign it on the outside as well.

'xaybz' ~~ / $<rx> = <$rx> /;
# 「xaybza」
#  rx => 「xaybza」
#   0 => 「x」
#   1 => 「y」
#   2 => 「za」

'xaybz' ~~ / $0 = <$rx> /;
# 「xaybza」
#  0 => 「xaybza」
#   0 => 「x」
#   1 => 「y」
#   2 => 「za」

Note that <…> is a sub-match, so the $0,$1,$2 from the $rx will never be on the top-level.


The result of doing the match is being matched when going outside the regex. This will work:

my $rx = '(.*)a(.*)b(.*)';
'xaybz' ~~ rx/$<result>=<$rx>/;
say $<result>;
# OUTPUT: «「xaybz」␤ 0 => 「x」␤ 1 => 「y」␤ 2 => 「z」␤»

Since, by assigning to a Match variable, you're accessing the raw Match, which you can then print. The problem is that <$rx> is, actually, a Match, not a String. So what you're doing is a Regex that matches a Match. Possibly the Match is stringified, and then matched. Which is the closest I can be to explaining the result