0

I having an issue using NSScanner.

I have this string: 195 058 042 yuiyui 123

and I'm trying to just return the integers. however, any number that contains a 0 before the space doesn't get scanned property.

 var note = "195 048 042 yuiyui 123"

let whitespaceAndPunctuationSet = NSMutableCharacterSet.whitespaceAndNewlineCharacterSet()
let numbersCharacterSet = NSCharacterSet.decimalDigitCharacterSet()

let stringScanner = NSScanner(string: note)

var value = 0
while stringScanner.scanInteger(&value) {
    print(value)
}

and this prints the following: 195 48 42

It it missing the 0 from '048' But I'm not sure why

it should print the following

195 048 42

Thanks

Tony
  • 656
  • 8
  • 20

1 Answers1

1

If you want to capture numeric substrings insider the longer string, NSRegularExpression is more appropriate:

let note = "195 048 042 yuiyui 123"

let regex = try! NSRegularExpression(pattern: "\\d+", options: [])

regex.enumerateMatchesInString(note, options: [], range: NSMakeRange(0, note.characters.count)) { result, flag, stop in
    guard let match = result else {
        // result is nil
        return
    }

    let range = match.rangeAtIndex(0)
    print((note as NSString).substringWithRange(range))
}
Code Different
  • 90,614
  • 16
  • 144
  • 163