首页 > 解决方案 > 正则表达式捕获 URL 中最后一个“/”之后的所有内容

问题描述

let url1 = "https://cdn0.tnwcdn.com/files/2020/01/exmaple1.jpg"
let url2 = "http://www.clker.com/cliparts/1/7/b/9/11974343961963318467fl.png"
let url3 = "https://images.squarespace-cdn.com/content/01+Seth+Easy+v1.gif"

我怎样才能在最后一个斜线之后捕捉到所有东西,所以在这种情况下:
exmaple1.jpg
11974343961963318467fl.png
01+Seth+Easy+v1.gif

标签: iosswiftregexurl

解决方案


使用components(separatedBy:)并从中获取last组件,即

url1.components(separatedBy: "/").last //"exmaple1.jpg"
url2.components(separatedBy: "/").last //"11974343961963318467fl.png"
url3.components(separatedBy: "/").last //"01+Seth+Easy+v1.gif"

或者您可以在使用创建lastPathComponentURL实例上使用url1, url2 and url3

URL(string: url1)?.lastPathComponent //"exmaple1.jpg"
URL(string: url2)?.lastPathComponent //"11974343961963318467fl.png"
URL(string: url3)?.lastPathComponent //"01+Seth+Easy+v1.gif"

推荐阅读