我正在尝试为我公司的站点编写 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/
结果总是
$1 = 15000000
//desired $1 = 15000000
$1 = 15000000/page/2
// desired $1 = 15000000 $2 = 2
$1 = 15000000/page/2/price/g10l20
// desired $1 = 15000000 $2 = 2 $3 = g10l20
$1 = 60000000/page/2/price//shipping//brand//sort/
// desired $1 = 60000000 $2 = 2 $3 = "" $4 = "" $5 = "" $6 = ""
我的理解是零个或多个量词将使它能够返回,并再次搜索“标志”模式,但显然情况并非如此。有人可以告诉我我做错了什么吗?
不幸的是,不可能从正则表达式中保留不确定数量的捕获。当使用 + * {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\/([^/]*)(\/.*)?/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句