Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if text contains only numbers?

Tags:

ios

swift

People also ask

How do you check if a string only contains letters and numbers?

Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise.

How do you know if a text contains only numbers in Python?

The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the . are not.

How do you check if a string contains only digits in Java?

Using Character.isDigit(char ch). If the character is a digit then return true, else return false.

How do I check if a string contains only numbers in SQL?

The ISNUMERIC() function tests whether an expression is numeric. This function returns 1 if the expression is numeric, otherwise it returns 0.


I find this solution, in Swift 3, to be cleaner

import Foundation

CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: yourString))

You just need to check whether the Set of the characters of your String is subset of the Set containing the characters from 0 to 9.

extension String {
    var isNumeric: Bool {
        guard self.characters.count > 0 else { return false }
        let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        return Set(self.characters).isSubset(of: nums)
    }
}

"".isNumeric // false
"No numbers here".isNumeric // false
"123".isNumeric // true
"Hello world 123".isNumeric // false

Expanding on the fantastic work from Luca above, here is the answer given written by way of Swift 5.

extension String {
    var isNumeric: Bool {
        guard self.count > 0 else { return false }
        let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        return Set(self).isSubset(of: nums)
    }
}

We have to check whether every character of the string is a digit or not and string must not be empty.

extension String {
   var isNumeric: Bool {
     return !(self.isEmpty) && self.allSatisfy { $0.isNumber }
   }
}

allSatisfy(_ predicate: (Character) throws -> Bool) rethrows -> Bool is a method which returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.

For reference: https://developer.apple.com/documentation/swift/array/2994715-allsatisfy

Example:

  1. let string = "123" string.isNumeric ---- returns true

  2. let string_One = "1@3" string_One.isNumeric ---- returns false