Regex Group in Perl: how to capture elements into array from regex group that matches unknown number of/multiple/variable occurrences from a string?

前端 未结 9 2156
遇见更好的自我
遇见更好的自我 2020-12-04 10:10

In Perl, how can I use one regex grouping to capture more than one occurrence that matches it, into several array elements?

For example, for a string:



        
9条回答
  •  长情又很酷
    2020-12-04 10:39

    I'm not saying this is what you should do, but what you're trying to do is write a Grammar. Now your example is very simple for a Grammar, but Damian Conway's module Regexp::Grammars is really great at this. If you have to grow this at all, you'll find it will make your life much easier. I use it quite a bit here - it is kind of perl6-ish.

    use Regexp::Grammars;
    use Data::Dumper;
    use strict;
    use warnings;
    
    my $parser = qr{
        <[pair]>+
             =(?:""|)
             var\d+
             <[MATCH=literal]> ** (,)
         \S+
    
    }xms;
    
    q[var1=100 var2=90 var5=hello var3="a, b, c" var7=test var3=hello] =~ $parser;
    die Dumper {%/};
    

    Output:

    $VAR1 = {
              '' => 'var1=100 var2=90 var5=hello var3="a, b, c" var7=test var3=hello',
              'pair' => [
                          {
                            '' => 'var1=100',
                            'value' => '100',
                            'key' => 'var1'
                          },
                          {
                            '' => 'var2=90',
                            'value' => '90',
                            'key' => 'var2'
                          },
                          {
                            '' => 'var5=hello',
                            'value' => 'hello',
                            'key' => 'var5'
                          },
                          {
                            '' => 'var3="a, b, c"',
                            'key' => 'var3',
                            'list' => [
                                        'a',
                                        'b',
                                        'c'
                                      ]
                          },
                          {
                            '' => 'var7=test',
                            'value' => 'test',
                            'key' => 'var7'
                          },
                          {
                            '' => 'var3=hello',
                            'value' => 'hello',
                            'key' => 'var3'
                          }
                        ]
    

提交回复
热议问题