【问题标题】:parsing String in swift快速解析字符串
【发布时间】:2023-02-22 16:22:32
【问题描述】:

解析以下字符串以读取名称和卷号的最佳方法是什么

"Student"={"Info"={}},
"Student"={"SchoolName"="abc","place"="abc","Info"={"Name"="student1","class"="class1"}},
"Student"={"SchoolName"="abc","place"="bbc,"Info"={"Name"="student2","class"="class1"}}

是否可以将此字符串直接解析为字典数组?

【问题讨论】:

  • 如果"bbc 后面有双引号,可以很容易地通过替换一些字符将其转换为 JSON。如果不是,那很难做到。
  • 是的,在 bbl 之后也有一个双引号

标签: swift string parsing


【解决方案1】:

如果这是一个 json,事情可能会容易得多。由于这是一个字符串,除了使用正则表达式模式之外,我看不到其他方法。

let string = """
"Student"={"Info":{}},
"Student"={"SchoolName":"abc","place":"abc","Info":{"Name":"student1","class":"class1"}},
"Student"={"SchoolName":"abc","place":"bbc","Info":{"Name":"student2","class":"class1"}}
"""

let pattern = #"Name":"([^"]+)","class":"([^"]+)""#

var array: [[String: String]] = []

let regex = try! NSRegularExpression(pattern: pattern, options: [])

regex.enumerateMatches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) { match, _, _ in
    if let match = match {
        
        let nameRange = Range(match.range(at: 1), in: string)!
        let classRange = Range(match.range(at: 2), in: string)!
        
        let name = String(string[nameRange])
        let classValue = String(string[classRange])
        
        array.append(["Name": name, "RollNumber": classValue])
    }
}
//output
print(array) //[["Name": "student1", "RollNumber": "class1"], ["Name": "student2", "RollNumber": "class1"]]

print(array[0]["Name"]) //Optional("student1")
print(array[0]["RollNumber"]) //Optional("class1")

仅供参考:如果这是 JSON 的一部分,则将其解码为字符串。不要尝试解码为字符串。

【讨论】:

    【解决方案2】:

    如果保证所有键都包含在双引号中,您可以通过将 = 字符替换为 : 并添加缺少的大括号和方括号,将字符串转换为有效的 JSON。

    var string = """
    "Student"={"Info"={}},
    "Student"={"SchoolName"="abc","place"="abc","Info"={"Name"="student1","class"="class1"}},
    "Student"={"SchoolName"="abc","place"="bbc","Info"={"Name"="student2","class"="class1"}}
    """
    
    string = string.replacingOccurrences(of: "=", with: ":")
    string = string.replacingOccurrences(of: ""Student", with: "{"Student")
    string = "[" + string.replacingOccurrences(of: "},", with: "}},") + "}]"
    

    匹配的结构是

    struct Root : Decodable {
        private enum CodingKeys: String, CodingKey { case student = "Student"}
        
        let student: Student?
    }
    
    struct Student : Decodable {
        private enum CodingKeys: String, CodingKey { case schoolName = "SchoolName", place, info = "Info" }
    
        let schoolName: String?
        let place: String?
        let info: Info
    }
    
    struct Info : Decodable {
        private enum CodingKeys: String, CodingKey { case name = "Name", className = "class" }  
    
        let name: String?
        let className: String?
    }
    

    你可以解码并显示数据

    do {
        let result = try JSONDecoder().decode([Root].self, from: Data(string.utf8))
        for item in result where item.student?.info.name != nil {
            let info = item.student!.info
            print("Name", info.name!, "Class", info.className ?? "No class available")
        }
    } catch {
        print(error)
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-26
      • 2020-02-28
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多