Perl 6 中的递归正则表达式? [英] Recursive regular expression in Perl 6?
问题描述
我一直在试图弄清楚如何在 Perl 6 中执行递归正则表达式.例如,一个平衡括号匹配器,它将匹配 ((())())
(((((())())
.
I've been trying to figure out how to do a recursive regular expression in Perl 6. For a toy example, a balanced parentheses matcher, which would match ((())())
inside (((((())())
.
PCRE 示例:
/\((?R)?\)/
Onigmo 示例:(?<paren>\(\g<括号>*\))
我认为这样做可以:
my regex paren {
'(' ~ ')' <paren>*
}
或者更简单的
my regex paren {
'(' <paren>* ')'
}
但是失败了
No such method 'paren' for invocant of type 'Match'
in regex paren at ...
推荐答案
你需要明确你正在调用一个 my
范围的正则表达式:
You need to make explicit that you're calling a my
-scoped regex:
my regex paren {
'(' ~ ')' <&paren>*
}
注意已添加的 &
.与此:
Notice the &
that has been added. With that:
say "(()())" ~~ /^<&paren>$/ # 「(()())」
say "(()()" ~~ /^<&paren>$/ # Nil
虽然有时确实可以在不明确编写 &
的情况下逃脱,但在使用它时确实可以:
While it's true that you can sometimes get away without explicitly writing the &
, and indeed could when using it:
say "(()())" ~~ /^<paren>$/ # 「(()())」
say "(()()" ~~ /^<paren>$/ # Nil
这只是因为编译器发现在词法作用域中定义了一个名为 paren
的正则表达式,所以将
语法编译成那个.对于递归情况,在解析正则表达式之后才安装声明,因此需要明确.
This only works because the compiler spots there is a regex defined in the lexical scope with the name paren
so compiles the <paren>
syntax into that. With the recursive case, the declaration isn't installed until after the regex is parsed, so one needs to be explicit.
这篇关于Perl 6 中的递归正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!