简体   繁体   中英

Remove a directory from a URL with regex

I have a site with the following URL structure in places:

www.sitename.com/folder/sub_folder/item

What I need to do is remove the sub_folder part so that it displays as:

www.sitename.com/folder/item

Is there a regex expression for that?

Not sure if there's a regex expression, but you should be able to parse, try splitting on '/', then removing everything between the first and last instance, then recombine with '/'

So if string s="www.sitename.com/folder/sub_folder/item"; string newUrl=s.split('/')[0]+"/"+s.split('/')[s.split('/').length];

or something along those lines

In Python, you could do:

str1 = "www.sitename.com/folder/sub_folder/item"

str2 = re.sub(r'/\w*(/\w*)$',r'\1',str1)

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