简体   繁体   中英

How can I extract an unknown substring from a string in Swift 4?

Using swift 4, I need to parse a string to get substrings that will always be different. For example:

let str = "[33376:7824459] Device Sarah's Phone (Hardware: D21AP, ECID: 8481036056622, UDID: 76e6bc436fdcfd6c4e39c11ed2fe9236bb4ec, Serial: F2LVP5JCLY)"

let strRange = str.range(of: "(?<=Device )(?= (Hardware)", options: .regularExpression)
print(strRange!)

I would think this would output "Sarah's Phone"

I'm not getting any errors on this code, but it's also not working. What am I doing wrong?

Several problems:

  1. You have a lookahead and lookbehind here, but nothing that would actually match any characters, so it'll never match anything except an empty string.

  2. You didn't properly escape the parenthesis in your lookahead.

  3. You should use if let or guard let , rather than ! , to unwrap the optional. Otherwise, you'll get a crash when you encounter an input string that doesn't match the pattern.

  4. I'm not sure why you'd expect print(strRange) to output text. strRange is a range, not a string or a substring.

This sample will fix your problems:

import Foundation

let str = "[33376:7824459] Device Sarah's Phone (Hardware: D21AP, ECID: 8481036056622, UDID: 76e6bc436fdcfd6c4e39c11ed2fe9236bb4ec, Serial: F2LVP5JCLY)"

if let strRange = str.range(of: "(?<=Device ).*(?= \\(Hardware)", options: .regularExpression) {
    print(str[strRange])
} else {
    print("Not Found")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM