如何在swift 4中获取字符串中文本的索引?
来自服务器的字符串为:如何在swift 4中获取字符串中文本的索引?,swift,string,Swift,String,来自服务器的字符串为: "Please review the work schedule for personnel associated with this device\nhttps://test.abcdxyz.com/media?q=kp97k73a9omm" 我需要从以下字符串中提取url: “” 如何在swift 4中执行此操作 阅读了有关字符串的内容后,我发现: if msg.contains("https://") { let x = msg.range(of: "https
"Please review the work schedule for personnel associated with this device\nhttps://test.abcdxyz.com/media?q=kp97k73a9omm"
我需要从以下字符串中提取url:
“”
如何在swift 4中执行此操作
阅读了有关字符串的内容后,我发现:
if msg.contains("https://") {
let x = msg.range(of: "https://")?.lowerBound
let str = msg.substring(from: x!)
print(str)
}
NSDataDetecter也是一个很酷的解决方案。
在这种情况下,哪一个更可靠???智能解决方案是
您不需要从匹配中创建范围来提取子字符串,有一个方便的url
属性。您可以使用它来轻松检测字符串中的url
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)
}
更多详情:
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)
}