是否有 Ruby 的 Regexp.names 的 Perl 等价物?

Is there a Perl equivalent for Ruby's Regexp.names?

在 Ruby 中,您可以使用 names 方法提取正则表达式的命名捕获组:

/(?<foo>.)(?<bar>.)(?<baz>.)/.names
#=> ["foo", "bar", "baz"]

这种方法是否有 Perl 等价物?我可以像这样提取名称:

while ( $re =~ m/\?<(.+?)>/g ) {
    say ;
}

但我不知道 robust/efficient/elegant 解决方案如何。

已编辑:我知道您可以在匹配后获取名称,但我需要在使用正则表达式之前提取名称。

匹配成功后可以提取组名:

my $re = qr/(?<foo>.)(?<bar>.)(?<baz>.)/;
'abc' =~ $re;
say for keys %-;

另见 Tie::Hash::NamedCapture

PPIx::Regexp::capture_names:

foreach my $name ( $re->capture_names() ) {
      print "Capture name '$name'\n";
 }

This convenience method returns the capture names found in the regular expression.

我没有尝试过这个模块,所以我不确定它是否是一个 100% 可靠的提取你想要的信息的方法。

另请参阅@ikegami 对 this question which led me to re-read perldoc re 的回答:

regnames($all)

Returns a list of all of the named buffers defined in the last successful match. If $all is true, then it returns all names defined, if not it returns only names which were involved in the match.

如此接近,但又不完全是。我不知道在 Perl 中以 Ruby 的 .names 的方式对正则表达式模式进行内省的内置方法。