正则表达式不捕获重复的可选捕获

Regex not capturing repeating optional captures

我正在尝试为我公司的网站编写 URL 重写正则表达式。 URL 将始终以 category/.+ 开头,之后最多可以添加 5 个额外的标签。使用我当前的正则表达式,它总是在类别之后捕获 .+,然后将其后的所有内容添加到该捕获组。 示例数据

/category\/(.+)(?:\/(?:page|price|shipping|sort|brand)\/(.*))*/
mysite.com/category/15000000
mysite.com/category/15000000/page/2
mysite.com/category/15000000/page/2/price/g10l20
mysite.com/category/60000000/page/2/price//shipping//brand//sort/

结果总是

 = 15000000
    //desired  = 15000000
 = 15000000/page/2
    // desired  = 15000000  = 2
 = 15000000/page/2/price/g10l20
    // desired  = 15000000  = 2  = g10l20
 = 60000000/page/2/price//shipping//brand//sort/
    // desired  = 60000000  = 2  = ""  = ""  = ""  = ""

我的理解是,零个或多个量词会使它返回并再次搜索 "flag" 模式,但显然不是这种情况。有人可以告诉我我做错了什么吗?

遗憾的是,无法从正则表达式中保留不确定数量的捕获。当使用 + * {n} 等重复捕获时,仅返回最近捕获的组。

如您所知,您最多可以有 5 个标签,您可以像这样重复相关块 5 次:

/category\/([^/]*)(?:\/(page|price|shipping|sort|brand)\/([^/]*))?(?:\/(page|price|shipping|sort|brand)\/([^/]*))?(?:\/(page|price|shipping|sort|brand)\/([^/]*))?(?:\/(page|price|shipping|sort|brand)\/([^/]*))?(?:\/(page|price|shipping|sort|brand)\/([^/]*))?/

这太丑陋了,允许重复标签,如果要添加更多标签,则需要扩展正则表达式。

最简洁的解决方案可能是在 $1 中捕获类别 ID,在 $2 中捕获其余参数字符串 - 您需要让应用程序解析它,这样可以更巧妙地完成它在正则表达式中。

/category\/([^/]*)(\/.*)?/