user6702783 user6702783 - 3 months ago 14
Swift Question

Regex for decimal number and blank Swift

I want a regex in swift matches all decimal numbers and integers, the requirement is following:

Reject these non-numbers:
. (single decimal point)
2.2.2 (two or more decimal points in any order)
-. (negative decimal point)
+. (plus decimal point)
(empty string)


Any help appreciated.

Answer

Instead of a regex, why not just try converting the String to a Float. You can put the following in a Swift playground to see that it works:

func isNumber(s: String) -> Bool {
    return Float(s) != nil
}

// Your criteria
isNumber(".")     // false
isNumber("2.2.2") // false
isNumber("-.")    // false
isNumber("+.")    // false
isNumber("")      // false

// Validity check
isNumber("2.2") // true
isNumber("2")   // true
isNumber("-2")  // true