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

Viewed 402

I want to match against a programmatically-constructed regex, containing a number of (.*) capture groups. I have this regex as a string, say

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

I would like to interpolate that string as a regex and match for it. The docs tell me <$rx> should do the trick (i.e. interpolate that string as a regex), but it doesn't. Compare the output of a match (in the perl6 REPL):

> 'xaybz' ~~ rx/<$rx>/
「xaybz」

vs the expected/desired output, setting apart the capture groups:

> 'xaybz' ~~ rx/(.*)a(.*)b(.*)/
「xaybz」
 0 => 「x」
 1 => 「y」
 2 => 「z」

Comments

One unappealing way I can do this is to EVAL my regex match (also in the REPL):

> use MONKEY; EVAL "'xaybz' ~~ rx/$rx/";
「xaybz」
 0 => 「x」
 1 => 「y」
 2 => 「z」

So while this does give me a solution, I'm sure there's a string-interpolation trick I'm missing that would obviate the need to rely on EVAL..

3 Answers

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

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.

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」
Related