title: Perl regular expression: match nested brackets
body: <p>I'm trying to match nested <code>{}</code> 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:</p>
  
  <pre><code>my @matches = $str =~ /\{(?:\{.*\}|[^\{])*\}|\w+/sg;
  
  foreach (@matches) {
      print "$_\n";
  }
  </code></pre>
  
  <p>At certain times this works as expected. For instance, if <code>$str = "abc {{xyz} abc} {xyz}"</code> I obtain:</p>
  
  <pre>
  abc
  {{xyz} abc}
  {xyz}
  </pre>
  
  <p>as expected. But for other input strings it does not function as expected. For example, if <code>$str = "{abc} {{xyz}} abc"</code>, the output is:</p>
  
  <pre>
  {abc} {{xyz}}
  abc
  </pre>
  
  <p>which is not what I expected. I would have wanted <code>{abc}</code> and <code>{{xyz}}</code> 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?</p>