perl正则表达式递归
??? 今天在chinaunix上看到有个贴,问 ??? 设最外层括号为第 1 层,请问怎么样能够除去 1 对第 2 层的括号,保留其他括号?
???
???? 解决方案一:
????
???? 解决方案二:
????
???? $str =~ /
???? (/()???????? # 分组1: $1匹配左括号 ???? (?=???????? # 整体是1个环视,这样,第1次匹配成功会从第1个左括号开始,第2个次匹配成功会从第2个左括号开始,以此类推 ??????? (???????? # 分组2: $2匹配括号里的内容加上$3 ??????????????? (?:??????? # 分组不捕获 ??????????????????????? [^()]????????????? # 要么不包括括号 ??????????????????????? | ??????????????????????? (?1)(?2)??????? # 要么是分组1加上分组2的递归 ??????????????? )+ ??????????????? (/)) # 分组3:$3匹配右括号 ??????? ) ????? ) ????? /xg;
————————————————————分割线————————————————————
???? http://perldoc.perl.org/perlre.html上有介绍perl 5.10以上的正则表达式新特性
????
(?PARNO) (?-PARNO) (?+PARNO) (?R) (?0)
Similar to PARNO is a sequence of digits (not starting with 0) whose value reflects the paren-number of the capture buffer to recurse to. The following pattern matches a function foo() which may contain balanced parentheses as the argument.
If the pattern was used as follows
the output produced should be the following:
If there is no corresponding capture buffer defined,then it is a fatal error. Recursing deeper than 50 times without consuming any input string will also result in a fatal error. The maximum depth is compiled into perl,so changing it requires a custom build. The following shows how using negative indexing can make it easier to embed recursive patterns inside of a
Note that this pattern does not behave the same way as the equivalent PCRE or Python construct of the same form. In Perl you can backtrack into a recursed group,in PCRE and Python the recursed into group is treated as atomic. Also,modifiers are resolved at compile time,so constructs like (?i:(?1)) or (?:(?i)(?1)) do not affect how the sub-pattern will be processed. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |