简体   繁体   English

PCRE中的递归正则表达式和组搜索

[英]Recursive regex and group searching in PCRE

I have a routing system in this form: website/(:option)(:option)(:option(:option)) or website/archive(/:year(/:month(-:day))) (/page/:page) . 我有这样一种路由系统: website/(:option)(:option)(:option(:option))website/archive(/:year(/:month(-:day))) (/page/:page) The ( ) represents an optional path and :string represents a variable that will be replaced. ( )表示可选路径, :string表示将被替换的变量。 In case of nested parentheses, I need all variables to continue (there may be an unlimited number of parentheses). 在嵌套括号的情况下,我需要所有变量才能继续(可能有无限数量的括号)。

I'm using PCRE in PHP. 我在PHP中使用PCRE。 I need to select all the (:string) , so I thought about this regex : \\([^\\(\\)]*:[^\\(\\)]+\\) . 我需要选择所有的(:string) ,所以我想到了这个正则表达式: \\([^\\(\\)]*:[^\\(\\)]+\\) I experience problems with recursive and group regex searching. 我在递归和组正则表达式搜索中遇到问题。

Example: website/archive(/2015(/:month(:day))) will select (/:month(:day)) 例如: website/archive(/2015(/:month(:day)))将选择(/:month(:day))
Example: website/archive(/:year(/03(27))) will select (/:year(/03(27))) 例如: website/archive(/:year(/03(27)))将选择(/:year(/03(27)))

Regexr 正则表达式

Can someone explain to me how the recursion works and if it's even possible to do it? 有人可以向我解释递归的工作原理,甚至可以做到吗?

try this pattern 试试这个模式

 (\\((?:[^()]|(?R))*\\)) 

Demo 演示版


after reading comment below, use this pattern, check against sub-pattern #1 阅读下面的评论后,请使用此模式,并对照子模式#1进行检查

\(([^():\r\n]*:[^()]+(\((?:[^()]|(?2))*\))\))

Demo 演示版
you may remove \\r\\n if it is not a multi-line input 如果不是多行输入,则可以删除\\r\\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM