'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.
Solution 1:[1]
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??»
Solution 2:[2]
The two answers I expected to see have already been posted, they are:
- "
{}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,
- 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | codesections |
| Solution 2 |
