I'm trying to match nested {} brackets with a regular expressions in Perl so that I can extract certain pieces of text from a file. This is what I have currently:
my @matches = $str =~ /\{(?:\{.*\}|[^\{])*\}|\w+/sg;
foreach (@matches) {
    print "$_\n";
}
At certain times this works as expected. For instance, if $str = "abc {{xyz} abc} {xyz}" I obtain:
abc
{{xyz} abc}
{xyz}
as expected. But for other input strings it does not function as expected. For example, if $str = "{abc} {{xyz}} abc", the output is:
{abc} {{xyz}}
abc
which is not what I expected. I would have wanted {abc} and {{xyz}} to be on separate lines, since each is balanced on its own in terms of brackets. Is there an issue with my regular expression? If so, how would I go about fixing it?
 
     
     
     
     
     
     
     
    