在两个字符串之间获取字符串Swift

时间:2018-09-26 07:08:53

标签: swift string substring

我有以下字符串:

"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=[[[(.*?),}

如何正确提取此字符串?谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

使用components(separatedBy:)

var str = "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\"]"

str.components(separatedBy: "\"")[1] // "encendedor"

答案 1 :(得分:1)

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

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")