Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you confirm a string only contains numbers in Swift? [duplicate]

Tags:

regex

ios

swift

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?

like image 829
Orkhan Alizade Avatar asked Dec 18 '15 11:12

Orkhan Alizade


People also ask

How do you check if a string contains only digits 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 .

How do you check if a string is an integer in Swift?

main.swift var x = 25 if x is Int { print("The variable is an Int.") } else { print("The variable is not an Int.") }


2 Answers

Here is the solution you can get all digits from String.

Swift 3.0 :

 let testString = "asdfsdsds12345gdssdsasdf"

 let phone = testString.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")

 print(phone)
like image 99
TwoStraws Avatar answered Oct 02 '22 09:10

TwoStraws


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 +

like image 33
NSAnant Avatar answered Oct 02 '22 10:10

NSAnant