How can I store regex captures in an array in Perl?

后端 未结 7 1197
孤城傲影
孤城傲影 2020-12-01 03:38

Is it possible to store all matches for a regular expression into an array?

I know I can use ($1,...,$n) = m/expr/g;, but it seems as though that can on

相关标签:
7条回答
  • 2020-12-01 04:06

    Sometimes you need to get all matches globally, like PHP's preg_match_all does. If it's your case, then you can write something like:

    # a dummy example
    my $subject = 'Philip Fry Bender Rodriguez Turanga Leela';
    my @matches;
    push @matches, [$1, $2] while $subject =~ /(\w+) (\w+)/g;
    
    use Data::Dumper;
    print Dumper(\@matches);
    

    It prints

    $VAR1 = [
              [
                'Philip',
                'Fry'
              ],
              [
                'Bender',
                'Rodriguez'
              ],
              [
                'Turanga',
                'Leela'
              ]
            ];
    
    0 讨论(0)
提交回复
热议问题