in reply to Determining if you have balanced delimiters

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.

  • Comment on Re (tilly) 1: Determining if you have balanced delimiters