gpt4 book ai didi

swift - 获取两个字符串之间的字符串 Swift

转载 作者:行者123 更新时间:2023-11-28 10:37:42 24 4
gpt4 key购买 nike

我有以下字符串:

"Notes[9219:1224244] [BoringSSL] Function boringssl_context_get_peer_sct_list: line 1757 received sct extension length is less than sct data length [[["encendedor","lighter",null,null,1]],null,"en"]"

我只想提取第一次出现的引号之间的字符串,在本例中为“encendedor”。我尝试了以下代码,这是我从 this question. 中了解到的

//finalTrans has the full string that needs to be shortened
let finalTrans = (String(data: data, encoding: .utf8)!)
let regex = try! NSRegularExpression(pattern:"[[[(.*?),", options: [])
var results = [String]()
regex.enumerateMatches(in: finalTrans, options: [], range: NSMakeRange(0, finalTrans.utf16.count)) { result, flags, stop in
if let r = result?.range(at: 1), let range = Range(r, in: finalTrans) {
results.append(String(finalTrans[range]))
}
}
//prints the new string
print(results)

我目前遇到这个错误:

Thread 6: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=2048 "The value “[[[(.*?),” is invalid." UserInfo={NSInvalidValue=[[[(.*?),}

我怎样才能正确提取这个字符串?谢谢您的帮助。

最佳答案

您还可以使用范围在两个字符串之间进行切片。

extension String {

func slice(from: String, to: String) -> String? {

return (range(of: from)?.upperBound).flatMap { substringFrom in
(range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
String(self[substringFrom..<substringTo])
}
}
}
}

let slicedString = yourString.slice(from: "\"", to: "\"") // Optional("encendedor")

关于swift - 获取两个字符串之间的字符串 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52511905/

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