简体   繁体   中英

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) . The ( ) represents an optional path and :string represents a variable that will be replaced. 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. I need to select all the (:string) , so I thought about this regex : \\([^\\(\\)]*:[^\\(\\)]+\\) . I experience problems with recursive and group regex searching.

Example: website/archive(/2015(/:month(:day))) will select (/:month(:day))
Example: website/archive(/:year(/03(27))) will select (/: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

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

Demo
you may remove \\r\\n if it is not a multi-line input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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