如何从模式中获取未知数量的捕获? [英] How do I grab an unknown number of captures from a pattern?

查看:46
本文介绍了如何从模式中获取未知数量的捕获?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个模式:

<cell> cell1=cell2 <pin> pin1=pin2 pin3=pin4 <type> type1=type2

如您所见,模式可以有多个值(在这种情况下,pin 有 2 组 pin 名称).金额未知.

As you can see, the pattern could have multiple values (in this case pin has 2 sets of pin names). The amount is unknown.

我将如何解析这个?这是我到目前为止所拥有的,但它没有帮助,因为它没有考虑模式是否有超过 2 组引脚.

How would I parse this? Here is what I have so far, but it is not helpful as it does not take into account if the pattern has more than 2 sets of pins.

my $pattern = "<cell> cell1=cell2 <pin> pin1=pin2 pin3=pin4 <type> type1=type2";

if ( $pattern =~ m#\<cell\> (\w*=\w*) \<pin\> (\w*=\w*) \<type\> (\w*=\w*)#) {

my $cell_name = $1;
my $pin_name = $2;
my $type_name = $3;
}

如您所见,这仅在只有一组引脚名称时才有效.但是我希望它能够适应多组未知的引脚名称.我想我必须像数组或散列一样构造,但我不确定考虑到未知的多个引脚集,获取这些值的最佳方法是什么.

as you can see, this will only work if there is only one set of pin names. However I want it to be able to adjust to multiple unknown sets of pin names. I think I would have to construct like an array or hash, but I am not really sure what is the best way of grabbing these values taking into account the unknown multiple pin sets.

我希望能够将 cell_name、pin_name 和 type_name 存储为数组或带有值集的散列.

I would like to be able to store the cell_name,pin_name and type_name as an array or hash with the sets of values.

推荐答案

你的问题比 为什么我得到第一个更棘手仅捕获组? 但其中一些想法可能会有所帮助.诀窍是停止思考以单一模式完成所有事情.

Your problem is a bit trickier than Why do I get the first capture group only? but some of those ideas may help. The trick is to stop thinking about doing everything in a single pattern.

如果这确实是您的输入,我很想在 = 周围匹配一组事物.在列表上下文中匹配,例如分配给散列,返回匹配列表:

If that's really your input, I'd be tempted to match groups of things around an =. Matching in list context, such as assigning to a hash, returns the list of matches:

use Data::Dumper;

my $input = "<cell> cell1=cell2 <pin> pin1=pin2 pin3=pin4 <type> type1=type2";
my %values = $input =~ m/ (\S+) = (\S+) /gx;

print Dumper( \%values );

= 之前的东西成为键,之后的东西成为值:

The things before the = become keys and the things after become the values:

$VAR1 = {
          'pin1' => 'pin2',
          'type1' => 'type2',
          'cell1' => 'cell2',
          'pin3' => 'pin4'
        };

但生活可能并不那么容易.示例名称可能实际上没有 pincell 等.

But life probably isn't that easy. The example names probably don't really have pin, cell, and so on.

不过,我还喜欢做另一件事,因为我怀念 sscan 带来的所有乐趣.您可以通过一次匹配字符串的一部分来遍历字符串,然后在下一场比赛中,从上次中断的地方开始.首先是整件事:

There's another thing I like to do, though, because I miss having all that fun with sscan. You can walk a string by matching part of it at a time, then on the next match, start where you left off. Here's the whole thing first:

use v5.10;

use Data::Dumper;

my $input = "<cell> cell1=cell2 <pin> pin1=pin2 pin3=pin4 <type> type1=type2";

my %hash;
while( 1 ) {
    state $type;

    if( $input =~ /\G < (.*?) > \s* /xgc ) {
        $type = $1;
        }
    elsif( $input =~ /\G (\S+) = (\S+) \s* /xgc ) {
        $hash{$type}{$1}{$2}++;
        }
    else { last }
    }

print Dumper( \%hash );

还有数据结构,这真的无关紧要,可以是您喜欢的任何内容:

And the data structure, which really doesn't matter and can be anything that you like:

$VAR1 = {
          'type' => {
                      'type1' => {
                                   'type2' => 1
                                 }
                    },
          'pin' => {
                     'pin1' => {
                                 'pin2' => 1
                               },
                     'pin3' => {
                                 'pin4' => 1
                               }
                   },
          'cell' => {
                      'cell1' => {
                                   'cell2' => 1
                                 }
                    }
        };

但让我们先谈谈他的.首先,所有匹配项都在标量上下文中,因为它们位于 if-elsif-else 分支的条件部分.这意味着他们只会进行下一场比赛.

But let's talk about his for a moment. First, all of the matches are in scalar context since they are in the conditional parts of the if-elsif-else branches. That means they only make the next match.

然而,我已经用 \G 锚定了每个模式的开始.当我在标量上下文中使用 /g 标志时,这使得模式匹配在字符串的开头或前一个成功匹配停止的位置.

However, I've anchored the start of each pattern with \G. This makes the pattern match at the beginning of the string or the position where the previous successful match left off when I use the /g flag in scalar context.

但是,我想尝试几种模式,所以其中一些会失败.这就是 /c 标志的用武之地.它不会在失败时重置匹配位置.这意味着 \G 锚点不会在匹配失败时重置.所以,我可以尝试一种模式,如果这不起作用,则从相同位置开始下一个.

But, I want to try several patterns, so some of them are going to fail. That's where the /c flag comes in. It doesn't reset the match position on failure. That means the \G anchor won't reset on an unsuccessful match. So, I can try a pattern, and if that doesn't work, start at the same position with the next one.

所以,当我遇到尖括号中的东西时,我会记住那种类型.直到我匹配尖括号中的另一个东西,这就是我匹配的东西的类型.现在,当我匹配 (\S+) = (\S+) 时,我可以将匹配分配给正确的类型.

So, when I encounter something in angle brackets, I remember that type. Until I match another thing in angle brackets, that's the type of thing I'm matching. Now when I match (\S+) = (\S+), I can assign the matches to the right type.

要观察这种情况,您可以输出记住的字符串位置.每个标量维护自己的光标,pos(VAR) 返回该位置:

To watch this happen, you can output the remembered string position. Each scalar maintains its own cursor and pos(VAR) returns that position:

use v5.10;

use Data::Dumper;

my $input = "<cell> cell1=cell2 <pin> pin1=pin2 pin3=pin4 <type> type1=type2";

my %hash;
while( 1 ) {
    state $type;

    say "Starting matches at " . ( pos($input) // 0 );
    if( $input =~ /\G < (.*?) > \s* /xgc ) {
        $type = $1;
        say "Matched <$type>, left off at " . pos($input);
        }
    elsif( $input =~ /\G (\S+) = (\S+) \s* /xgc ) {
        $hash{$type}{$1}{$2}++;
        say "Matched <$1|$2>, left off at " . pos($input);
        }
    else {
        say "Nothing left to do, left off at " . pos($input);
        last;
        }
    }

print Dumper( \%hash );

在 Dumper 输出之前,您现在可以看到标量上下文中的全局匹配遍历字符串:

Before the Dumper output, you now see the global matches in scalar context walk the string:

Starting matches at 0
Matched <cell>, left off at 7
Starting matches at 7
Matched <cell1|cell2>, left off at 19
Starting matches at 19
Matched <pin>, left off at 25
Starting matches at 25
Matched <pin1|pin2>, left off at 35
Starting matches at 35
Matched <pin3|pin4>, left off at 45
Starting matches at 45
Matched <type>, left off at 52
Starting matches at 52
Matched <type1|type2>, left off at 63
Starting matches at 63
Nothing left to do, left off at 63

<小时>

最后,作为奖励,这是一个递归的体面语法.对于您提供的内容,这肯定是矫枉过正,但在更棘手的情况下做得更好.除了说它产生相同的数据结构外,我不会解释它:


Finally, as a bonus, here's a recursive decent grammar that does it. It's certainly overkill for what you've provided, but does better in more tricky situations. I won't explain it other than to say it produces the same data structure:

use v5.10;

use Parse::RecDescent;
use Data::Dumper;

my $grammar = <<~'HERE';
    startrule: context_pairlist(s)
    context_pairlist: context /\s*/ pair(s)
    context: '<' /[^>]+/ '>'
        { $::context = $item[2] }
    pair: /[A-Za-z0-9]+/ '=' /[A-Za-z0-9]+/
        { main::build_hash( $::context, @item[1,3] ) }
    HERE

my $parser = Parse::RecDescent->new( $grammar );

my %hash;
sub build_hash {
    my( $context, $name, $value ) = @_;
    $hash{$context}{$name}{$value}++;
    }

my $input = "<cell> cell1=cell2 <pin> pin1=pin2 pin3=pin4 <type> type1=type2";
$parser->startrule( $input );

say Dumper( \%hash );

这篇关于如何从模式中获取未知数量的捕获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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