以任意顺序匹配可选组件 [英] Match Optional Components in Any Order

查看:64
本文介绍了以任意顺序匹配可选组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个URL,该URL可以包含用于过滤结果的参数的任意组合.这两个参数是类型和排序.如果URL中存在type,则它必须是"article","opinion","review"或"media".如果URL中存在sort,则它必须是以下之一:date-desc,date-asc,views-desc,views-asc,comments-desc,comments-asc.

I have a URL that can contain any combination of parameters used in filtering results. The two params are type and sort. If type exists in the URL, it has to be either 'article', 'opinion', 'review', or 'media. If sort exists in the URL, it has to be one of the following: date-desc, date-asc, views-desc, views-asc, comments-desc, comments-asc.

现在,我所拥有的表达式仅将类型和排序都与URI相匹配.它与不包含任何参数的URL不匹配.我希望表达式匹配没有任何参数的URL和只有一个参数的URL.它也必须以任天堂,PC,PlayStation或Xbox开头.

Right now, the expression I have only matches URI's with both type and sort. And it doesn't match URL's that contain neither params. I would like the expression to match URL's without any parameters and URL's that have only one parameter. It also has to start with either nintendo, pc, playstation, or xbox.

这是我的示例字符串:

xbox/type:article/sort:date-desc  (match)
nintendo/type:media/sort:comments-asc  (match)
pc/sort:views-desc  (no match)
playstation/type:opinion/ (no match)
playstation/sort:views-asc (no match)
xbox/sort:views-asc/type:article (no match)
playstation/type:media/sort:views-asc (match)
xbox (no match)

以上所有组合都必须匹配.这是我目前的表情:

All of the above combinations need to match. Here is my current expression:

(nintendo|pc|playstation|xbox)[\/]((type\:(article|opinion|reivew|media))[\/](sort\:(date-desc|date-asc|views-desc|views-asc|comments-desc|comments-asc)))

这是Regex101链接: http://regex101.com/r/eN0tJ5

Here is the Regex101 link: http://regex101.com/r/eN0tJ5

推荐答案

您可以在任何原子后缀?以使其可选,因此您可能会得到如下结果:

You can suffix any atom with ? to make it optional, so you could end up with something like this:

(nintendo|pc|...)(/type:(article|media|...))?(/sort:(date|views|comments)-(asc|desc))?

这篇关于以任意顺序匹配可选组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆