简体   繁体   中英

Regular expression of partial url

I have the following:

https://www.example.com/my-suburl/sub-dept/xx-xxxx-xx-yyyyyy/

Im trying to find the 'yyyyy' in the url so far I have:

(.*)\/sub-dept\/(.*[^\/])\/([^\/]*)$

Which matches on:

https://www.example.com/my-suburl

and

xx-xxxx-xx-yyyyyy

However like i say I need the 'yyyyy' specific match

NON-C#-BASED SOLUTION

If xx are numbers in the actual strings, just use

\d+(?=\/$)

Or else, use

[^-\/]*(?=\/?$)

See Demo 1 and Demo 2

Note that in JS, there is no look-behind, thus, if you must check if /sub-dept/ is in front of the substring you need, you will have to rely on capturing group mechanism:

\/sub-dept\/[^\/]*-([^-\/]*)\/?

See yet another demo

ORIGINAL ANSWER

Here is a regex you can use

(?<=/sub-dept/[^/]*-)[^/-]*(?=/$)

See demo

The regex matches a substring that contains 0 or more characters other than a / or - that is...

  • (?<=/sub-dept/[^/]*-) preceded with /sub-dept/ followed by 1 or more characters other than / and then a hyphen
  • (?=/$) - is followed by a / symbol right at the end of the string.

Or, there is a non-regex way: split the string by / , get the last part and split by - . Here is an example (without error/null checking for demo sake):

var result = text.Trim('/').Split('/').LastOrDefault().Split('-').LastOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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