In a PHP script, what regex should I use to check for mismatched parentheses in a string? Things that I want to allow include:
Why it's not possible with a regex
The other answers are all correct, but I just want to put in a plug for theoretical computer science... this is a case where knowing the theory gives an actual practical advantage.
A regex corresponds to a deterministic finite automaton (DFA), but paren matching require a context-free grammar, which can be realized as a finite automaton (PDA) but not by a DFA.
Because of this, without a lot of extra brain-work, we know that the answer is no, and we don't have to worry that there is something we're just overlooking. So, you can be confident in the above answers, and not worry that the authors are just overlooking something when they give that answer.
Almost all compiler books will talk about this, here's a quick overview:
http://books.google.com/books?id=4LMtA2wOsPcC&pg=PA94&lpg=PA94&dq=push-down+finite+automata&source=bl&ots=NisYwNO1r0&sig=ajaSHFXwpPOWG8IfbcfKoqzS5Wk&hl=en&ei=m26cSdf6DZGYsAPB-6SsAg&sa=X&oi=book_result&resnum=6&ct=result