算一个qr正则表达式中的捕获组? [英] Count the capture groups in a qr regex?

查看:71
本文介绍了算一个qr正则表达式中的捕获组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个项目,该项目有一次从ftp服务器获取文件列表。此时,它要么返回文件的arrayref,要么如果传递了可选的正则表达式引用(即 qr ),则使用grep过滤列表。此外,如果 qr 具有捕获组,则将捕获的段视为版本号,并返回一个hashref,其中键是版本,值是文件名(如果没有捕获组,则将其作为数组返回)。代码看起来像(略有简化)

I am working on a project which at one point gets a list of files from an ftp server. At that point it either returns an arrayref of files OR if an optional regex reference (i.e. qr), is passed it filters the list down using grep. Further if that qr has a capture group, it treats the captured section as a version number and returns instead a hashref where the keys are the versions and the values are the file names (which would have been returned as the array if no capture groups). The code looks like (simplified slightly)

sub filter_files {
  my ($files, $pattern) = @_;
  my @files = @$files;
  unless ($pattern) {
    return \@files;
  }

  @files = grep { $_ =~ $pattern } @files;
  carp "Could not find any matching files" unless @files;

  my %versions = 
    map { 
      if ($_ =~ $pattern and defined $1) { 
        ( $1 => $_ )
      } else {
        ()
      }
    } 
    @files;

  if (scalar keys %versions) {
    return \%versions;
  } else {
    return \@files;
  }
}

此实现尝试创建哈希并在返回时返回成功了。我的问题是,我是否可以检测到 qr 具有捕获组并且仅尝试创建散列?

This implementation tries to create the hash and returns it if it succeeds. My question, is can I detect that the qr has a capture group and only attempt to create the hash if it does?

推荐答案

您可以使用类似以下内容的东西:

You could use something like:

sub capturing_groups{
    my $re = shift;
    "" =~ /|$re/;
    return $#+;
}

say capturing_groups qr/fo(.)b(..)/;

输出:

2

这篇关于算一个qr正则表达式中的捕获组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆