简体   繁体   English

以存在条件为条件捕获群体

[英]Capturing groups with condition on existence

I have url like 我有喜欢的网址

http://localhost:8080/web/group/555/content/777/image?arg1=1&arg2=2#anchor

There are 3 parts i'm trying to get: group number , content number and the view type value which is "image" in the sample above (can be one of predefined set of values and it is guarateed no values with text "group" or "content"). 我试图获得3个部分: 组编号内容编号视图类型值,在上面的示例中为“图像”(可以是一组预定义的值,并且不能保证没有任何带有文本“组”的值或“内容”)。

I got following regexp so far (it has 3 capturing groups i need) 到目前为止,我一直关注regexp(我需要3个捕获组)

/.*(?:\/group\/([\d]+))(?:\/content\/([\d]+))\/([\w]+).*/g

which works only when all the parts are present. 仅当所有零件都存在时才起作用。

The problem is any of the part can be absent (except "view type"), so next urls are also valid: 问题是任何部分都可能不存在(“视图类型”除外),因此下一个URL也是有效的:

http://localhost:8080/web/content/777/image
// which has $1="", $2="777", $3="image"
http://localhost:8080/web/nogroup/555/content/777/video
// which has $1="", $2="777", $3="video"
http://localhost:8080/web/audio
// which has $1="", $2="", $3="audio"

Is there a way to tell regexp: if there is no matching for the group $1 set its value to ""? 有没有办法告诉正则表达式:如果组$ 1没有匹配项,将其值设置为“”?

You need to add a question mark ? 您需要添加问号? after each of the groups that can be present but aren't necessary for a match and it will automatically populate them with "" : 在每个可能出现但不需要比赛的组之后,它将自动用""填充它们:

/.*(?:\/group\/([\d]+))?(?:\/content\/([\d]+))?\/([\w]+).*/g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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