Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string between two strings Swift

I have the following string:

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

I only want to extract the string between the first occurrences of quotation marks, which in this case is "encendedor". I tried the following code, which I understood from 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)

I am currently getting this error:

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

How can I properly extract this string? Thanks for the help.

like image 407
apaul Avatar asked Aug 26 '26 11:08

apaul


1 Answers

You can also use range to slice between two strings.

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")
like image 75
Retterdesdialogs Avatar answered Aug 28 '26 07:08

Retterdesdialogs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!