Home > Blockchain >  Grab particular words from a string
Grab particular words from a string

Time:05-18

I have JSON data which I am attempting to grab only the words including age. I plan on then grabbing all ages over 21. I've gotten as far as separating each word in the string as a separate string, but I can't see find a way to traverse each age.

let JSON = """
{"data":"key=IAfpK, age=58, key=WNVdi, age=4, key=jp9zt, age=47, key=0Sr4C, age=68, key=CGEqo, age=76"}
"""
struct DataObject: Decodable {
    let data: String
 
}


func grabAges() {
    let jsonData = JSON.data(using: .utf8)!
    let dataObject: DataObject = try! JSONDecoder().decode(DataObject.self, from: jsonData)
    
    var arr = dataObject.data.components(separatedBy: ",")
    
    //print(dataObject.data)
    
}

CodePudding user response:

Regular Expression can do it pretty well, it's not needed to split the string.

The pattern "\bage=(\d )" searches for the string age= (at the beginning of a word) followed by one or more digits and captures the numeric part.

With compactMap you can map (and filter) the search results to Int values

let json = """
{"data":"key=IAfpK, age=58, key=WNVdi, age=4, key=jp9zt, age=47, key=0Sr4C, age=68, key=CGEqo, age=76"}
"""
struct DataObject: Decodable {
    let data: String
}

func grabAges() {
    let jsonData = json.data(using: .utf8)!
    let dataObject = try! JSONDecoder().decode(DataObject.self, from: jsonData)
    
    let data = dataObject.data
    let regex = try! NSRegularExpression(pattern: #"\bage=(\d )"#)
    let ages = regex.matches(in: data, range: NSRange(data.startIndex..., in: data))
        .compactMap { match -> Int? in
            guard let range = Range(match.range(at: 1), in: data),
            let age = Int(data[range]), age > 21 else { return nil }
            return age
        }
    print(ages)
}

grabAges()
  • Related