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 2117
遇见更好的自我
遇见更好的自我 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!

    0 讨论(0)
  • 2020-12-04 10:59
    #!/usr/bin/perl
    
    use strict; use warnings;
    
    use Text::ParseWords;
    use YAML;
    
    my $string =
        "var1=100 var2=90 var5=hello var3=\"a, b, c\" var7=test var3=hello";
    
    my @parts = shellwords $string;
    print Dump \@parts;
    
    @parts = map { { split /=/ } } @parts;
    
    print Dump \@parts;
    
    0 讨论(0)
  • This one will provide you also common escaping in double-quotes as for example var3="a, \"b, c".

    @a = /(\w+=(?:\w+|"(?:[^\\"]*(?:\\.[^\\"]*)*)*"))/g;
    

    In action:

    echo 'var1=100 var2=90 var42="foo\"bar\\" var5=hello var3="a, b, c" var7=test var3=hello' |
    perl -nle '@a = /(\w+=(?:\w+|"(?:[^\\"]*(?:\\.[^\\"]*)*)*"))/g; $,=","; print @a'
    var1=100,var2=90,var42="foo\"bar\\",var5=hello,var3="a, b, c",var7=test,var3=hello
    
    0 讨论(0)
提交回复
热议问题