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.

apaul
  • 308
  • 3
  • 13
  • 2
    Various solutions (with and without regex) at https://stackoverflow.com/questions/31725424/swift-get-string-between-2-strings-in-a-string. – Martin R Sep 26 '18 at 07:11
  • The regular expression needs all `[` to be escaped. `.*?` makes no sense either – Sulthan Sep 26 '18 at 07:12

2 Answers2

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")
Retterdesdialogs
  • 3,180
  • 1
  • 21
  • 42
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"
Vatsal Manot
  • 17,695
  • 9
  • 44
  • 80