我有一些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
}
请告诉我你的想法。谢谢!
答案 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!)
}