【发布时间】:2015-01-07 20:11:16
【问题描述】:
TL;DR:有没有办法指定条件,以便开始元素必须匹配其配对的结束元素?
示例位于on regex101.com。
=====
正则表达式中的平衡元素通常通过递归处理。这意味着可以定位嵌套的{...{...{...}...}...}。
此外,PCRE 允许 (?(DEFINE)...) 构造,它允许您定义各种模式而无需实际开始匹配。
在正则表达式中
# Define the opening and closing elements before the recursion occurs
(?(DEFINE)
(?<open_curly>\{)
(?<close_curly>\})
# ... other definitions here ...
(?<open>\g'open_curly')
(?<close>\g'close_curly')
)
# Match the opening element
(\g'open'
(?>
# For recursion, don't match either the opening or closing element
(?!\g'open'|\g'close')(?s:.)
|
# Recurse this captured pattern
(?-1)
)*
# Match the closing element
\g'close')
元素是{ 和} 字符,可以匹配诸如
{{{}}}
{ test1 { test2 { test3 { test4 } } } }
我想包含其他打开/关闭元素,例如[ 和],或--[ 和--],所以在(?(DEFINE)) 中包含这些元素:
(?<open_square>\[)
(?<close_square>\])
(?P<open_pascal>(?i:\bbegin\b))
(?P<close_pascal>(?i:\bend\b))
(?P<open_lua>--\[)
(?P<close_lua>--\])
(?<open>\g'open_curly'|\g'open_square'|\g'open_pascal'|\g'open_lua')
(?<close>\g'close_curly'|\g'close_square'|\g'close_pascal'|\g'close_lua')
这样做的错误在于将开始元素与其结束元素配对,从而允许--[ 与} 组合,这是不可取的。
有没有办法在这样的正则表达式中创建打开/关闭对?
【问题讨论】:
-
一般情况下,正则表达式无法检测平衡元素,因为正则表达式是状态机,但您需要堆栈机。
-
@Mark 模式匹配库允许您使用递归(需要堆栈)来匹配嵌套结构。看我的回答。一些实现 (.NET) 使用平衡组,这也是一个堆栈。所以你肯定可以将嵌套结构与这些模式相匹配——只是你不能再称它们为 regular。
-
谢谢。这对我来说是一个新信息。