[英]Remove Part of String Before the Last Forward Slash
我目前正在处理的程序从网站检索URL并将它们放入列表中。 我想得到的是URL的最后一部分。
所以,如果我的URL列表中的第一个元素是"https://docs.python.org/3.4/tutorial/interpreter.html"
我想删除"interpreter.html"
之前的所有内容。
我可以使用函数,库或正则表达式来实现吗? 我查看了其他Stack Overflow帖子,但解决方案似乎不起作用。
这是我的几次尝试中的两个:
for link in link_list:
file_names.append(link.replace('/[^/]*$',''))
print(file_names)
&
for link in link_list:
file_names.append(link.rpartition('//')[-1])
print(file_names)
看看str.rsplit
。
>>> s = 'https://docs.python.org/3.4/tutorial/interpreter.html'
>>> s.rsplit('/',1)
['https://docs.python.org/3.4/tutorial', 'interpreter.html']
>>> s.rsplit('/',1)[1]
'interpreter.html'
并使用RegEx
>>> re.search(r'(.*)/(.*)',s).group(2)
'interpreter.html'
再搭配其位于最后间的第二组/
字符串和结束。 这是RegEx中贪婪技术的贪婪用法。
小注 - link.rpartition('//')[-1]
在于你试图匹配//
而不是/
。 因此删除link.rpartition('/')[-1]
中的extra /
as。
这不需要正则表达式。
import os
for link in link_list:
file_names.append(os.path.basename(link))
你可以使用rpartition() :
>>> s = 'https://docs.python.org/3.4/tutorial/interpreter.html'
>>> s.rpartition('/')
('https://docs.python.org/3.4/tutorial', '/', 'interpreter.html')
并采取返回的3元素元组的最后一部分:
>>> s.rpartition('/')[2]
'interpreter.html'
只需使用string.split:
url = "/some/url/with/a/file.html"
print url.split("/")[-1]
# Result should be "file.html"
split为您提供了一个由“/”分隔的字符串数组。 [-1]为您提供数组中的最后一个元素,这就是您想要的。
如果您打算使用正则表达式,这应该有效
for link in link_list:
file_names.append(link.replace('.*/',''))
print(file_names)
这是一个更通用,正则表达式的方法:
re.sub(r'^.+/([^/]+)$', r'\1', "http://test.org/3/files/interpreter.html")
'interpreter.html'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.