How to get index of a text in a string in swift 4?

Viewed 139

There is a string from server as:

"Please review the work schedule for personnel associated with this device\nhttps://test.abcdxyz.com/media?q=kp97k73a9omm"

I need to extract the url from this string that is :

"https://test.abcdxyz.com/media?q=kp97k73a9omm"

How can I do this in swift 4 ??

What I found after reading about String is :

if msg.contains("https://") {
 let x = msg.range(of: "https://")?.lowerBound
 let str = msg.substring(from: x!)
            print(str)
}

NSDataDetecter is also a cool solution for this. Which one is more reliable in this case ??

2 Answers

A smart solution is NSDataDetector

let string = "Please review the work schedule for personnel associated with this device\nhttps://test.abcdxyz.com/media?q=kp97k73a9omm"

let types: NSTextCheckingResult.CheckingType = [.link]
if let detector = try? NSDataDetector(types: types.rawValue),
   let link = detector.firstMatch(in: string, range: NSRange(string.startIndex..., in: string)) {
    print(link.url!)
}

You don't need to create a Range from the match to extract the substring, there is a convenient url property.

You can use NSDataDetector which makes easy to detect URLs inside a string

let inputString = "Please review the work schedule for personnel associated with this device\nhttps://test.abcdxyz.com/media?q=kp97k73a9omm"

let urlDetector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let getMatches = urlDetector.matches(in: inputString, options: [], range: NSRange(location: 0, length: inputString.utf16.count))

for match in getMatches {
    guard let range = Range(match.range, in: inputString) else { continue }
    let url = inputString[range]
    print(url)
}

More detail: https://www.hackingwithswift.com/example-code/strings/how-to-detect-a-url-in-a-string-using-nsdatadetector

Related