简体   繁体   中英

How do I find the ranges of numbers in an NSString using the current locale?

I have an NSString like "abcd 12.3 efgh 45,6 ijlk". I want to find the ranges of the numbers in the string, using the current locale; so if it's EN then I'll get the ranges of "12.3", "45" and "6"; but if it's FR I'll get "12", "3" and "45,6".

Using NSScanner (Swift version, hacked together in Playground):

var str : NSString = "abcd 12.3 efgh 45,6 ijlk"
let scanner = NSScanner(string: str as String)
scanner.locale = NSLocale(localeIdentifier: "fr_FR")
scanner.charactersToBeSkipped = nil

let characterSet = NSCharacterSet(charactersInString: "-0123456789");
let result = NSMutableArray()

while (!scanner.atEnd) {
    var decimal = NSDecimal()

    if scanner.scanDecimal(&decimal) {
        result.addObject(NSDecimalNumber(decimal: decimal))
    } else {
        if !scanner.scanUpToCharactersFromSet(characterSet, intoString: nil) {
            break
        }
    }
}

result // [12, 3, 45.6]

The important point is to set the locale with scanner.locale . If you set the locale to en_US you instead get [12.3, 45, 6]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM