用于检查字符串是否具有不匹配的括号的正则表达式?

2022-08-30 19:29:04

在PHP脚本中,我应该使用哪个正则表达式来检查字符串中不匹配的括号?我想允许的事情包括:

  • 这是(好的)
  • 这(是)(好的)

我想阻止的事情:

  • 这是)坏(
  • 这也是(不好)
  • 这是(坏(太)

谢谢!

更新:你们都是摇滚。使用正则表达式执行此操作似乎比它应该有的要棘手,而这些类型的2nd级答案是使stackoverflow变得美丽的原因。感谢您的链接和伪代码。我不知道该给谁答案,所以我向所有我无法接受答案的人道歉。


答案 1

正则表达式不是适合这项工作的工具。手动扫描字符串。

伪代码:

depth = 0
for character in some_string:
    depth += character == '('
    depth -= character == ')'
    if depth < 0:
       break

if depth != 0:
   print "unmatched parentheses"

答案 2

你可以用正则表达式来做到这一点 - PHP使用的PCRE允许递归模式。PHP手册给出了一个几乎完全符合您需求的示例

\(((?>[^()]+)|(?R))*\)

这与任何正确括号的子字符串匹配,只要它以括号开头和结尾即可。如果你想确保整个字符串是平衡的,允许像“wiggedy(wiggedy)(wiggedy(wack))”这样的字符串,以下是我想出的:

^((?:[^()]|\((?1)\))*+)$

以下是对模式的解释,这可能比混淆更具启发性:

^             Beginning of the string
(             Start the "balanced substring" group (to be called recursively)
  (?:         Start the "minimal balanced substring" group
    [^()]     Minimal balanced substring is either a non-paren character
    |         or
    \((?1)\)  a set of parens containing a balanced substring
  )           Finish the "minimal balanced substring" group
  *           Our balanced substring is a maximal sequence of minimal
              balanced substrings
  +           Don't backtrack once we've matched a maximal sequence
)             Finish the "balanced substring" pattern
$             End of the string

在提出这些类型的正则表达式时,有很多关于效率和正确性的考虑因素。小心。


推荐