Swift - 从字符串中提取双精度值

Swift - Extract Double value from String

如何检查我的字符串是否只包含 [0-9].
我想从我的字符串中删除所有其他符号。 如果用户输入任何 String

var anyString:String = “3f00b6r.beAwes0me4me”

我想从中提取所有数字(包括一个 . 如果存在)并删除所有其他字符。

var myDouble:Double = 3006.04

有人知道怎么做吗?

你可以使用 NSRegularExpression,像这样:

// First set up error for checking
var error:NSError?

// Create regular expression pattern to search for numbers one digit in length or longer
let regexString = NSRegularExpression(pattern: "[0-9]{1,}.[0-9]{1,}|[0-9]{1,}", options: nil, error: &error)
// example string
let string = "find the number 10.19"
// get the string length
let strLength = count(string)
// To return the result first of all obtain the range of the first match if there is one, if let used here because NSRegularExpression returns an optional (we could of checked earlier, but I didn't)
if let rangeOfFirstMatch = regexString?.rangeOfFirstMatchInString(string, options: nil, range: NSMakeRange(0, strLength))
{
    // if a range has been found that isn't equal to NSNotFound then build a range for the found string
if !NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0)) {
advance(string.startIndex, rangeOfFirstMatch.length)
    let r =  Range(start: advance(string.startIndex, rangeOfFirstMatch.location), end: advance(string.startIndex, rangeOfFirstMatch.location+rangeOfFirstMatch.length))
// return the value
    let substringForFirstMatch = string.substringWithRange(r)
    println("Here's your match: \(substringForFirstMatch)")
    }
}

还有 String.stringByTrimmingCharactersInSet(),它会更干净、更快捷,但功能不多。例如,如果你这样做,上面的字符串也会被 returned:

let set = NSMutableCharacterSet.alphanumericCharacterSet()
set.addCharactersInString(" ")
set.removeCharactersInString("0123456789.")

string.stringByTrimmingCharactersInSet(set)

但是,如果字符串更改为 "find the number ??...10.19....",那么 stringByTrimmingCharactersInSet() 会让您失望,而 return "??...10.19...." 而正则表达式版本会保持不变。

为了使事情更简单,可以像这样编写一个字符串扩展,用于 return 在一个 Double 或 Int 类型的字符串中输入多个数字:

extension String {

    func stringsMatchingRegularExpression(expression exp:String, error err:NSErrorPointer) -> [String]? {
        var strArray:[String]?
        var rangeArray:[NSRange]?
        let strLength = count(self)
        var startOfRange = 0
        if let regexString = NSRegularExpression(pattern: exp, options: nil, error: err) {

            while startOfRange <= strLength {
                let rangeOfMatch = regexString.rangeOfFirstMatchInString(self, options: nil, range: NSMakeRange(startOfRange, strLength-startOfRange))
                if let rArray = rangeArray {
                    rangeArray = rArray + [rangeOfMatch]
                }
                else {
                    rangeArray = [rangeOfMatch]
                }
                startOfRange = rangeOfMatch.location+rangeOfMatch.length


            }
            if let ranArr = rangeArray {
                for r in ranArr {

                    if !NSEqualRanges(r, NSMakeRange(NSNotFound, 0)) {
                        advance(self.startIndex, r.length)
                        let r =  Range(start: advance(self.startIndex, r.location), end: advance(string.startIndex, r.location+r.length))
                        // return the value
                        let substringForMatch = self.substringWithRange(r)
                        if let sArray = strArray {
                            strArray = sArray + [substringForMatch]
                        }
                        else {
                            strArray = [substringForMatch]
                        }

                    }

                }
            }
        }
        return strArray
    }
}
let myString = "one number is 7.5, another is 20"
let subStringArray = myString.stringsMatchingRegularExpression(expression: "[0-9]{1,}.[0-9]{1,}|[0-9]{1,}", error: nil)
subStringArray?[0] // 7.5
subStringArray?[1] // 20

Swift 2.0 扩展更新

extension String {

    func stringsMatchingRegularExpression(expression exp:String) -> [String]? {
        var strArray:[String]?
        var rangeArray:[NSRange]?
        let strLength = self.characters.count
        var startOfRange = 0
        do {
         let regexString = try NSRegularExpression(pattern: exp, options: [])
            while startOfRange <= strLength {
                let rangeOfMatch = regexString.rangeOfFirstMatchInString(self, options: [], range: NSMakeRange(startOfRange, strLength-startOfRange))
                if let rArray = rangeArray {
                    rangeArray = rArray + [rangeOfMatch]
                }
                else {
                    rangeArray = [rangeOfMatch]
                }
                startOfRange = rangeOfMatch.location+rangeOfMatch.length


            }
            if let ranArr = rangeArray {
                for r in ranArr {

                    if !NSEqualRanges(r, NSMakeRange(NSNotFound, 0)) {
                        self.startIndex.advancedBy(r.length)
                        let r =  Range(start: self.startIndex.advancedBy(r.location), end: self.startIndex.advancedBy(r.location + r.length))

                        // return the value
                        let substringForMatch = self.substringWithRange(r)
                        if let sArray = strArray {
                            strArray = sArray + [substringForMatch]
                        }
                        else {
                            strArray = [substringForMatch]
                        }

                    }

                }
            }
        }        catch {
        }




        return strArray
    }
}
let myString = "one number is 7.5, another is 20"
let subStringArray = myString.stringsMatchingRegularExpression(expression: "[-+]?\d+.?\d+")
subStringArray?[0] // 7.5
subStringArray?[1] // 20

Swift 3.0 扩展更新

extension String {

    func stringsMatchingRegularExpression(expression exp:String) -> [String]? {
        var strArray:[String]?
        var rangeArray:[NSRange]?
        let strLength = self.characters.count
        var startOfRange = 0
        do {
            let regexString = try NSRegularExpression(pattern: exp, options: [])
            while startOfRange <= strLength {
                let rangeOfMatch = regexString.rangeOfFirstMatch(in: self, options: [], range: NSMakeRange(startOfRange, strLength-startOfRange))
                if let rArray = rangeArray {
                    rangeArray = rArray + [rangeOfMatch]
                }
                else {
                    rangeArray = [rangeOfMatch]
                }
                startOfRange = rangeOfMatch.location+rangeOfMatch.length


            }
            if let ranArr = rangeArray {
                for r in ranArr {

                    if !NSEqualRanges(r, NSMakeRange(NSNotFound, 0)) {
                        self.index(startIndex, offsetBy: r.length)

                        let r =  self.index(startIndex, offsetBy:r.location)..<self.index(startIndex, offsetBy:r.location + r.length)

                        // return the value
                        let substringForMatch = self.substring(with: r)
                        if let sArray = strArray {
                            strArray = sArray + [substringForMatch]
                        }
                        else {
                            strArray = [substringForMatch]
                        }

                    }

                }
            }
        }
        catch {
        // catch errors here
        }

        return strArray
    }
}
let myString = "one number is 7.5, another is 20"
let subStringArray = myString.stringsMatchingRegularExpression(expression: "[-+]?\d+.?\d+")
subStringArray?[0] // 7.5
subStringArray?[1] // 20