richsb richsb - 2 years ago 80
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:

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

} catch {

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

Answer Source

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

let str = "ip address:"

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download