简体   繁体   中英

Get filename without extension from URL with conditional

I've seen lots of examples with getting file names from URL or path, but am unable to solve this problem.

I have a URL that looks like below:

http://www.bob.net/john/john/ken/mary.html 

I need to get Mary if both /john/john exist in the URL. Otherwise I need to get ken if only /john exists in the path

I can get mary with \\/\\w*\\/\\w*\\/(\\w*)\\/(\\w*) but that's reliant on Mary being after the 4th slash.

How can I accomplish this?

EDIT - thanks for the responses so far.

Any chance of making this dynamic and getting just mary, if /john exists within the url? regardless of anything else?

try this pattern
^.*?[^\\/]\\/([^\\/]+)\\/(?:\\1\\/[^\\/]+\\/([^\\/.]+)|([^\\/]+))
Demo what you're looking for is the second capturing group

To get Mary if John is in the path, and John otherwise, use this:

^(?=.*john).*(mary)|.*(ken)

If there's a match, inspect match[1] and match[2] : only one will be set.

In Perl and PCRE you can do this a bit more compactly with conditionals or branch reset.

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