Regex for checking if a string has mismatched parentheses?

后端 未结 8 2164
一生所求
一生所求 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 05:49

    Your examples don't include any nested parentheses… if you aren't concerned with nesting, then this can be done using the following expression:

    ^[^()]*(?:\([^()]*\)[^()]*)*$
    

    This will match against all the strings in your "allow" list and fail against the strings in your "prevent" list. However, it will also fail against any string with nested parentheses. e.g. "this (is (not) ok)"

    As others have already pointed out, regular expressions are not the correct tool if you need to handle nesting.

提交回复
热议问题