richsb richsb - 6 months ago 11
Swift Question

Extracting numbers and characters from a text file in Swift

I'm reading in a text config file in swift and need to extract the numbers and decimals from an ip address. The config.txt file contains the line- ip address: 192.0.168.1

So far I have-

let path = "/config.txt"

do {
// Use contentsOfFile overload.
// ... Specify ASCII encoding.
// ... Ignore errors.
let data = try NSString(contentsOfFile: path, encoding: NSASCIIStringEncoding)

// If a value was returned, print it.


let str = data
let intString = str.componentsSeparatedByCharactersInSet(NSCharacterSet
.decimalDigitCharacterSet()
.invertedSet)
.joinWithSeparator("")

print(data)
print(intString)
} catch {
}


Of course this will return just the numbers of the ip address. I'm stumped at getting the correct format of 192.0.168.1

Answer

If there's always the same "ip address: " text before the IP address, then it's super simple:

let str = "ip address: 192.0.168.1"

if let intString = str.componentsSeparatedByString("address: ").last {
    print(intString)
}

Prints:

192.0.168.1