简体   繁体   English

如何从Swift 4中的字符串中提取未知子字符串?

[英]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. 使用swift 4,我需要解析一个字符串以获得总是不同的子字符串。 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 ! 你应该使用if letguard let ,而不是! , 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. 我不确定为什么你会期望print(strRange)输出文本。 strRange is a range, not a string or a substring. strRange是一个范围,而不是字符串或子字符串。

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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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