正则表达式(regular expression)有着强大的功能,但也不是万能的,匹配(match)匹配(balanced)的括号(parentheses)就是一个挺头疼的问题。不过perl正则表达式中的一个扩展(??{ code })却能很好的处理这个问题。直接就能把上下文无关文法(Content-Free Grammar, CFG)
P --> <empty> P --> ( P ) P --> P P
改写成对应的正则表达式
$paren = qr#|\((??{$paren})\)|(??{$paren})(??{$paren})#;
不过由于(??{$paren})(??{$paren})中的第一个(??{$paren})可以不断匹配0个字符,因此它不能正常工作,不过只要稍加修改,其等价形式
$paren = qr#|\((??{$paren})\)(??{$paren})?#;
就能够完成匹配balanced parentheses的工作了。
(??{ code })是动态正则表达式,code将在运行时求值,所求值再作为正则表达式。
This is a “postponed” regular subexpression. The “code” is evaluated at run time, at the moment this subexpression may match. The result of evaluation is considered as a regular expression and matched as if it were inserted instead of this construct.
其很重要的一个用途就是实现正则表达式的递归(recursion)。



Entries (RSS)