这可以在 php 中完成(使用 PCRE 引擎)。
下面只是一个例子。
您可以注释掉错误检查,然后插入边界构造
围绕正则表达式使其最终通过/失败。
最大的问题不是递归,而是定义内容边界
状况。我已经为你简化了。这些检查必须
保持任何你如何做,状态,堆栈......,都是一样的。
(此正则表达式是使用 RegexFormat 6 构建和测试的)
示例输入:
((( (1 and 2 and 3) or (9) or ( ( 4 and 5)) and 5 ) and 7) )
测试输出:
** Grp 0 - ( pos 0 , len 64 )
((( (1 and 2 and 3) or (9) or ( ( 4 and 5)) and 5 ) and 7) )
** Grp 1 - ( pos 1 , len 62 )
(( (1 and 2 and 3) or (9) or ( ( 4 and 5)) and 5 ) and 7)
** Grp 2 - NULL
** Grp 3 - NULL
** Grp 4 - NULL
正则表达式:
5/29 所有形式:
不允许使用空表单( )
不允许使用空表单) (
表单) and ( ok
表格) and 2 and ( ok
表格( 1 and 2 )ok
表格( 1 ) ok
表格) and 2 ) ok
表单( 1 and ( ok
形成( whitespace ( 或) whitespace ) ok
# (?s)(?:\(((?!\s*\))(?&core))\)|\s*([()]))(?(DEFINE)(?<core>(?>(?&content)|\((?:(?!\s*\))(?&core))\)(?!\s*\())+)(?<content>(?>(?<=\))\s*(?:and|or)\s*(?=\()|(?<=\))\s*(?:(?:and|or)\s+\d+)+\s*(?:and|or)\s*(?=\()|(?<=\()\s*\d+(?:(?:\s+(?:and|or)\s+)?\d+)*\s*(?=\))|(?<=\))\s*(?:(?:and|or)\s+\d+)+\s*(?=\))|(?<=\()\s*(?:\d+\s+(?:and|or))+\s*(?=\()|\s+)))
# //////////////////////////////////////////////////////
# // The General Guide to 3-Part Recursive Parsing
# // ----------------------------------------------
# // Part 1. CONTENT
# // Part 2. CORE
# // Part 3. ERRORS
(?s) # Dot-All modifier (used in a previous incarnation)
(?:
# ( # (1), Take off CONTENT (not used here)
# (?&content)
# )
# | # OR
\( # Open Paren's
( # (1), parens CORE
(?! \s* \) ) # Empty form '( )' not allowed
(?&core)
)
\) # Close Paren's
| # OR
\s*
( # (2), Unbalanced (delimeter) ERRORS
# - Generally, on a whole parse, these
# are delimiter or content errors
[()]
)
)
# ///////////////////////
# // Subroutines
# // ---------------
(?(DEFINE)
# core
(?<core> # (3)
(?>
(?&content)
|
\( # Open Paren's
(?:
(?! \s* \) ) # Empty form '( )' not allowed
(?&core)
)
\) # Close Paren's
(?! \s* \( ) # Empty form ') (' not allowed
)+
)
# content
(?<content> # (4)
(?>
(?<= \) ) # Form ') and ('
\s*
(?: and | or )
\s*
(?= \( )
|
(?<= \) ) # Form ') and 2 and ('
\s*
(?:
(?: and | or )
\s+
\d+
)+
\s*
(?: and | or )
\s*
(?= \( )
|
(?<= \( ) # Form '( 1 and 2 )'
\s*
\d+
(?:
(?:
\s+
(?: and | or )
\s+
)?
\d+
)*
\s*
(?= \) )
|
(?<= \) ) # Form ') and 2 )'
\s*
(?:
(?: and | or )
\s+
\d+
)+
\s*
(?= \) )
|
(?<= \( ) # Form '( 1 and ('
\s*
(?:
\d+
\s+
(?: and | or )
)+
\s*
(?= \( )
|
\s+ # Interstitial whitespace
# '( here (' or ') here )'
)
)
)