python - 使用正则表达式提取文件名

标签 python regex

我想创建一个正则表达式来提取网址的文件名

https://example.net/img/src/img.jpg

我想提取img1.jpg

我使用Python中的urlparse,但它以这种方式提取路径

img/src/img.jpg

如何使用正则表达式提取文件名

最佳答案

使用str.split和负索引

url = "https://example.net/img/src/img.jpg"
print(url.split("/")[-1])

输出:

img.jpg

或使用os.path.basename

import urlparse, os
url = "https://example.net/img/src/img.jpg"
a = urlparse.urlparse(url)
print(os.path.basename(a.path))   #--->img.jpg

关于python - 使用正则表达式提取文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50245419/

相关文章:

python - 时间序列数据的自定义损失函数

python - 如何在 python 中比较 ISO-8601 日期

python - 检测关键序列

javascript - 正则表达式/分割句子

regex - vim 在搜索和替换中使用通配符时交换子字符串

python - 使用 matplotlib 面向对象的接口(interface)使用 seaborn 进行绘图

python - 通过覆盖 __new__ 来装饰类方法不起作用?

regex - grep 如何匹配一些字母或行尾

c# - 字符串替换未按预期工作

php - preg_replace、preg_replace_callback 和数组到字符串的转换