user17227456
user17227456

Reputation: 1317

What is the correct Raku recursive regex syntax?

What or how is Raku recursive regex syntax and all match variable in Raku as on try

'hellohelloworldworld' ~~ m{ ^(h\w+?o) (?0) world  };
say "\n=$&"

seems to not work

Please help out solving these.

Upvotes: 8

Views: 249

Answers (2)

jubilatious1
jubilatious1

Reputation: 2289

The two answers I expected to see have already been posted, they are:

  1. " {} publication" of a match variable for use later within the same regex/matching operation (technically a backreference):
    > say $/ if 'hellohelloworldworld' ~~ m/ ^(h\w+?o) {} $0 world /;
    「hellohelloworld」
     0 => 「hello」
    > say $/ if 'hellohelloworldworld' ~~ m/ ^(h\w+?o) world /;
    「hellohelloworld」
     0 => 「hellohello」

and,

  1. use of Raku's dedicated " <~~> recursing-match" operator within the regex.

In true TMTOWTDI-spirit, there is however a third option, using Raku's :nd() adverb to achieve a sort of "poor-man's" recursion. Starting from the ['(' \w* ] grouping, you can successively pull out 「(bird」, 「(in」, and 「(nest」 from the input string (bird(in(nest))). Or all three at once (last example):

In the Raku REPL:

> my $nested = "(bird(in(nest)))";
(bird(in(nest)))
> say $nested;
(bird(in(nest)))
> say  $nested ~~ m:1st/ ['(' \w* ] /;
「(bird」
> say  $nested ~~ m:2nd/ ['(' \w* ] /;
「(in」
> say  $nested ~~ m:3rd/ ['(' \w* ] /;
「(nest」
> say  $nested ~~ m:nd(1..3)/ ['(' \w* ] /;
(「(bird」 「(in」 「(nest」)
>

Behind the scenes this is most likely using Raku's :position adverb or :continue adverb, in conjunction with Raku's $/.to match variable:

> say  $nested ~~ m/ ['(' \w* ] /;
「(bird」
> say  $nested ~~ m:pos($/.to)/ ['(' \w* ] / given $nested ~~ m/ ['(' \w* ] /;
「(in」
> say  $nested ~~ m:pos($/.to)/ ['(' \w* ] / given $nested ~~ (m/ ['(' \w* ] / && m:pos($/.to)/ ['(' \w* ] /);
「(nest」
> 

Again, Raku gives you a lot of different ways to approach the problem, which is one of the niceties of the language.

Upvotes: 3

codesections
codesections

Reputation: 9600

Raku has dedicated syntax for anonymous recursive regexes :<~~>.

Using this syntax, you could write the regex in your question as:

'hellohelloworldworld' ~~ m{ ^(h\w+?o) <~~>? world  };

say $/; # OUTPUT: «「hellohelloworld」␤
        #          0 => 「hellohello」␤»

Upvotes: 8

Related Questions