Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在swift 4中获取字符串中文本的索引?_Swift_String - Fatal编程技术网

如何在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)
}