How can I check, if searchView contains just numbers?
I found this:
if newText.isMatchedByRegex("^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$") { ... }
but it checks if text contains any number. How can I do, that if all text contains just numbers in Swift?
Check if a string contains only a number To check whether the string contains only numbers, we use the concept of set and CharacterSet. decimalDigits together. For a string to contains only a number, all the characters in that string must be a subset of CharacterSet. decimalDigits .
main.swift var x = 25 if x is Int { print("The variable is an Int.") } else { print("The variable is not an Int.") }
Here is the solution you can get all digits from String
.
let testString = "asdfsdsds12345gdssdsasdf"
let phone = testString.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
print(phone)
you can use "^[0-9]+$"
instade "^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$"
This will accept one or more digits, if you want to accept only one digit then remove +
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With