Regex for checking if a string has mismatched parentheses?

后端 未结 8 2160
一生所求
一生所求 2020-11-29 05:41

In a PHP script, what regex should I use to check for mismatched parentheses in a string? Things that I want to allow include:

  • This is (ok)
  • This (is)
8条回答
  •  我在风中等你
    2020-11-29 06:08

    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

提交回复
热议问题