swift - 来自字符串的子串

时间:2016-09-25 11:17:41

标签: ios swift substring

我有一些url字符串,如:

让url1 =" https://abc/help?user_info_id=5#help-article03"

让url2 =" https://cde?user_info_id=455&artical=4"

让url3 =" https://ghi/help?user_info_id=5"

现在我想从这些网址获取user_info_id。

url1返回5,url2返回455,url3返回5

这是我的代码

func getID(string: String) -> String {
    let range = string.rangeOfString("user_info_id=")
    guard let endIndex = range?.endIndex else { return "" }
    let remain = string.substringFromIndex(endIndex)

    let num = "0123456789"
    var result = ""
    for c in remain.characters {
        if num.containsString(String(c)) {
            result.append(c)
        } else {
            break
        }
    }
    return result
}

请告诉我你的想法。谢谢!

1 个答案:

答案 0 :(得分:4)

使用(NS)URLComponents并过滤查询项:

let url1 = "https://cde?user_info_id=455&artical=4"
if let components = NSURLComponents(string: url1),
  let queryItems = components.queryItems,
  let userInfoId = queryItems.filter({$0.name == "user_info_id"}).first where userInfoId.value != nil {
  print(userInfoId.value!)
}