0

How do I search for a range of Strings, I want to search userID

But userID may this time is "123", next time is "zxvcvb", so i can't use 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
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571

2 Answers2

0

Try this code :

let userID = "jshjdschd"
let url = "http://test/main/?Username=\(userID)#!/index.php"

    guard let firstIndex = url.index(of: "="),
        let secondIndex = url[firstIndex...].index(of: "#") else{
            print("UserId not found")
    }

let range = url.index(after: firstIndex)..<secondIndex
let mySubstring = url[range]
print(mySubstring) //jshjdschd
technerd
  • 14,144
  • 10
  • 61
  • 92
0

You can use a regex to get the range of the user ID between those two strings:

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"
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571