Regex for checking if a string has mismatched parentheses?

后端 未结 8 2145
一生所求
一生所求 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:09

    Regex is not the right tool for the job. Scan a string manually.

    Pseudo-code:

    depth = 0
    for character in some_string:
        depth += character == '('
        depth -= character == ')'
        if depth < 0:
           break
    
    if depth != 0:
       print "unmatched parentheses"
    

提交回复
热议问题