6

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.

2
  • 2
    Various solutions (with and without regex) at stackoverflow.com/questions/31725424/…. Commented Sep 26, 2018 at 7:11
  • The regular expression needs all [ to be escaped. .*? makes no sense either Commented Sep 26, 2018 at 7:12

2 Answers 2

17

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")
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.