我有以下网址字符串:
https://open.spotify.com/artist/7Ln80lUS6He07XvHI8qqHH?si=75tvlB1pQsW7xomeFfpGQA
我需要提取其中的7Ln80lUS6He07XvHI8qqHH
部分。如何在Swift中使用正则表达式执行此操作?
答案 0 :(得分:3)
您可以这样做:
let str = "https://open.spotify.com/artist/7Ln80lUS6He07XvHI8qqHH?si=75tvlB1pQsW7xomeFfpGQA"
guard let urlComponents = URLComponents(string: str),
let artistID = urlComponents.path.split(separator: "/").last
else {
fatalError("Can't find the artist")
}
let artistIdString = String(artistID) //"7Ln80lUS6He07XvHI8qqHH"
或更简洁地说:
guard let urlComponents = URLComponents(string: str) else {
fatalError("Can't find the artist")
}
let artistID = (urlComponents.path as NSString).lastPathComponent //"7Ln80lUS6He07XvHI8qqHH"
答案 1 :(得分:1)
使用lastPathComponent
中的URL
获得所需的结果,即
let str = "https://open.spotify.com/artist/7Ln80lUS6He07XvHI8qqHH?si=75tvlB1pQsW7xomeFfpGQA"
if let url = URL(string: str) {
print(url.lastPathComponent)
}
它将给出pathComponents
的{{1}}数组的最后一个元素。