How can I extract a string between matching braces in Perl?

前端 未结 7 838
再見小時候
再見小時候 2020-12-06 06:19

My input file is as below :

HEADER 
{ABC|*|DEF {GHI 0 1 0} {{Points {}}}}

{ABC|*|DEF {GHI 0 2 0} {{Points {}}}}

{ABC|*|XYZ:abc:def {GHI 0 22 0} {{Points {{         


        
7条回答
  •  醉话见心
    2020-12-06 06:45

    This can certainly be done with regex at least in modern versions of Perl:

    my @array = $str =~ /( \{ (?: [^{}]* | (?0) )* \} )/xg;
    
    print join "\n" => @array;
    

    The regex matches a curly brace block that contains either non curly brace characters, or a recursion into itself (matches nested braces)

    Edit: the above code works in Perl 5.10+, for earlier versions the recursion is a bit more verbose:

    my $re; $re = qr/ \{ (?: [^{}]* | (??{$re}) )* \} /x;
    
    my @array = $str =~ /$re/xg;
    

提交回复
热议问题