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

时间:2017-10-27 15:38:38

标签: regex url-rewriting ecma262

我正试图为我公司的网站写一个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 = ""

我的理解是零或更多量词将使它能够返回,并再次搜索"标志"模式,但显然不是这样。有人可以告诉我我做错了吗?

1 个答案:

答案 0 :(得分:1)

不幸的是,不可能从正则表达式中保留不确定数量的捕获。当使用+ * {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\/([^/]*)(\/.*)?/