Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am looping through all the links on a page and matching their href values against the following pattern:

([^/]+)/([0-9]+)/([^/]+)

Problem is there are 2 types of link formats on the page:

1. /video/123/slug
2. /video/123

Number 1. gets captured fine with the above regex but the 2nd fails. I want to make the third piece of the regex (the slug) optional so that both link formats return true when matched agains the regex. How to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
167 views
Welcome To Ask or Share your Answers For Others

1 Answer

Put the last bit in brackets of a non-capturing group and add a ?:

([^/]+)/([0-9]+)(?:/([^/]+))?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...