Group Group Group Group Group Group Group Group Group

Parsing text into array of objects


#1

Hello, I am new in Swift 4 and I would like to parse text string into array. My goal is to parse string of names and ages (could be written as Name Age and Age Name) into array of objects Person.

String could be: “George Swift 32, 44 Peter Cloud, Mary Table 18”

class Person {
var name = “”
var age = “”
}

Could anybody help me how to start and which function use for it?


#2

I made how to parse string, but still don’t know how to get age from string “George Swift 32” or “Mary Table 18”. Does anybody have some hint?

    let persons = "George Swift 32, 44 Peter Cloud, Mary Table 18"
    let arrayOfPersons : [String] = persons.components(separatedBy:",")

    class Person {
        var name = ""
        var age = ""
    }

    var personList = [Person]()

    for person in arrayOfPersons {
        let newPerson = Person()
        newPerson.name = person
        personList.append(newPerson)
    }

#3

I am closer again:-) in PHP I would use preg_match, but I am not able to rewrite it in Swift with NSRegularExpression, could any master help me please? :slight_smile:


#4

Hi @internetstream,
Having the Age in the string at random places is not a good idea, What happens if you have a name like “Henry the 4th 55” so is 4 the age or 55? If you set that the age is at the end, then you can take the last few characters and parse them for an age.

Regex can help but it will fail if you have no standard normalised format.

cheers,