user6702783
user6702783

Reputation: 223

Regex used in swift to check decimal input

In my application, there are a few textfields with decimal keyboard input. So I need a function to validate the number.

func valueCheck(check: Double) -> Double{
    let myRegex = "^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$"
    if check != nil && let match = check.rangeOfString(myRegex, options: .RegularExpressionSearch){
        return check
    }else{
        return 0.0
    }

}

If the number is not nil or invalid such as a few dots, then return the number. If the number is nil or invalid then return 0.0 I want to use regex but I have no idea how to use it in swift. Any help appreciated.

Upvotes: 2

Views: 4172

Answers (2)

Lightbeard
Lightbeard

Reputation: 4131

Swift 2

import Foundation

func valueCheck(d: Double) -> Double {   
    var result = 0.0
    do {
        let regex = try NSRegularExpression(pattern: "^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$", options: [])
        let results = regex.matchesInString(String(d), options:[], range: NSMakeRange(0, String(d).characters.count))
        if results.count > 0 {result = d}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
    }
    return result
}

Swift 3

import Foundation

func valueCheck(_ d: Double) -> Double {   
    var result = 0.0
    do {
        let regex = try RegularExpression(pattern: "^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$", options: [])
        let results = regex.matches(in: String(d), options: [], range: NSMakeRange(0, String(d).characters.count))
        if results.count > 0 {result = d}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
    }
    return result
}

Upvotes: 1

T.H404
T.H404

Reputation: 36

class func regexMatch(source:String,regexStr:String) -> Bool{
    let regex: NSRegularExpression?
    do{
        try regex = NSRegularExpression(
            pattern: regexStr,
            options: .CaseInsensitive)

    }catch{
        return false
    }

    if let matches = regex?.matchesInString(source,
                                            options: NSMatchingOptions(rawValue: 0),
                                            range: NSMakeRange(0, source.characters.count)) {
        return matches.count > 0
    } else {
        return false
    }
}

Upvotes: 1

Related Questions