Reputation: 33
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?
Upvotes: 1
Views: 128
Reputation: 17040
Several problems:
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.
You didn't properly escape the parenthesis in your lookahead.
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.
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")
}
Upvotes: 3