如何搜索一系列字符串

时间:2018-02-27 03:57:15

标签: swift string search range swift4

如何搜索一系列字符串, 我想搜索userID

但是这次userID可能是“123”, 下次是“zxvcvb”, 所以我不能使用offsetBy

let userID = "12345"
let URL = "http://test/main/?Username=\(userID)#!/index.php"
let firstIndex = URL.index(of: "=")
let secondIndex = URL.index(of: "#")
let range = firstIndex...secondIndex //error

1 个答案:

答案 0 :(得分:0)

您可以使用regex获取这两个字符串之间的用户ID范围:

let userID = "12345"
let pattern = "(?<=Username=)(.*)(?=#!)"
let link = "http://test/main/?Username=\(userID)#!/index.php"
if let range = link.range(of: pattern, options: .regularExpression) {
     let id = link[range]
     print("id:", id)    // "id: 12345\n"
}