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 2160
遇见更好的自我
遇见更好的自我 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:57

    You asked for a RegEx solution or other code. Here is a (mostly) non regex solution using only core modules. The only regex is \s+ to determine the delimiter; in this case one or more spaces.

    use strict; use warnings;
    use Text::ParseWords;
    my $string="var1=100 var2=90 var5=hello var3=\"a, b, c\" var7=test var3=hello";  
    
    my @array = quotewords('\s+', 0, $string);
    
    for ( my $i = 0; $i < scalar( @array ); $i++ )
    {
        print $i.": ".$array[$i]."\n";
    }
    

    Or you can execute the code HERE

    The output is:

    0: var1=100
    1: var2=90
    2: var5=hello
    3: var3=a, b, c
    4: var7=test
    5: var3=hello
    

    If you really want a regex solution, Alan Moore's comment linking to his code on IDEone is the gas!

提交回复
热议问题