It is very easy to remove the need for the .* - just don't use an RE solution. :-)

Though I find this cute, using an RE for this problem is like using a hammer as a screwdriver. It kinda works. But when you need to solve a slightly more delicate problem, it doesn't really. In this instance suppose we have several types of matched delimiters, (), [] and {}. Now go forth and check whether a given body of text balances! The RE fails horribly.

This is not a failing of REs, it is a matter of them being used outside of their area of competency.

REs are designed to state patterns that you can search a string for. They are bits and pieces that can be recognized and are really handy for that. However people like them so much that they try to use it to demonstrate that a document fits some format. This is a different kind of problem. What you want to do now is start thinking of this as a parsing problem, looking for tokens, etc.

As soon as you make that shift, the harder version of this problem becomes trivial. Maintain a stack of open tokens, when you come to closing ones pull them off and see if they match. If not then you have a problem. When you come to the end if any are left open you have another problem. This is conceptually easy and readily extensible.


In reply to Re (tilly) 1: Determining if you have balanced delimiters by tilly
in thread Determining if you have balanced delimiters by Ovid

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.