Search code examples
regexregex-groupraku

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


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..


Solution

  • 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