gpt4 book ai didi

swift - 如何在 swift 4 中获取字符串中文本的索引?

转载 作者:行者123 更新时间:2023-12-01 15:35:14 25 4
gpt4 key购买 nike

服务器有一个字符串:

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

我需要从这个字符串中提取网址:

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

我怎样才能在 swift 4 中做到这一点?

阅读有关 String 后我发现的是:

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

NSDataDetecter 也是一个很酷的解决方案。在这种情况下哪个更可靠??

最佳答案

一个聪明的解决方案是 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!)
}

您不需要从匹配中创建 Range 来提取子字符串,有一个方便的 url 属性。

关于swift - 如何在 swift 4 中获取字符串中文本的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60426712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com