正则表达式从URL字符串中提取Spotify艺术家ID

时间:2018-10-29 11:06:28

标签: ios swift

我有以下网址字符串:

https://open.spotify.com/artist/7Ln80lUS6He07XvHI8qqHH?si=75tvlB1pQsW7xomeFfpGQA

我需要提取其中的7Ln80lUS6He07XvHI8qqHH部分。如何在Swift中使用正则表达式执行此操作?

2 个答案:

答案 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}}数组的最后一个元素。