See Parse::YAPP. This implements a full grammar, which is a superset of what can be done with a regex.

Update: I just ran into Text::Balanced, which I suppose does exactly this. It's part of the Parse::RecDescent package. You should already have it if you've installed Switch.

A true regular expression is represented by a connected graph of nodes, and you move from state to state with each input token. It can't count, because it has no memory at all other than knowing what state it's in.

To count braces, you need a "Push-down automata", the next step up. It has a graph and a stack.

So, you could implement a P.D.A. by starting with foreach $char (split ('',$input)) {, switch to the current state, and push/pop a @array for the state. More specifically, push the open symbol so you can check against it for a matching close.

if $char is an open symbol, push it along with position. else if $char is a close symbol, pop the stack and verify that it's the matching type (error if not). popped position through current position is ballanced range. Save +that on answer list.
Error if stack underflows. When out of input, make sure stack is also empty else warning. Return list of ballanced position ranges.

—John


In reply to Re: Balancing braces without (??{}) by John M. Dlugosz
in thread Balancing braces without (??{}) by tshabet

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.