12

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?

Peter Hornsby
  • 4,208
  • 1
  • 25
  • 44
Orkhan Alizade
  • 7,379
  • 14
  • 40
  • 79

2 Answers2

37

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)
Community
  • 1
  • 1
TwoStraws
  • 12,862
  • 3
  • 57
  • 71
  • 1
    Will this NSCharacterSet include arabic type of numbers? I mean maybe user need only this type of numbers (1, 2, 3, 4, ...) but also keyboard may include such numbers (١٢٣). How can I check only (1, 2, 3)? – Сергей Олейнич Dec 18 '15 at 11:59
  • 1
    @СергейОлейнич, if you want to be sure about only specific characters are included in your set, you can define the character set by `+characterSetWithCharactersInString:` method. ([source](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCharacterSet_Class/#//apple_ref/occ/clm/NSCharacterSet/characterSetWithCharactersInString:)) – holex Dec 18 '15 at 12:24
6

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 +

NSAnant
  • 816
  • 8
  • 18
  • 1
    what about floating numbers? or negatives? are those not numbers anymore? – holex Dec 18 '15 at 12:16
  • "^[0-9]+(\.[0-9]+)?$" this will match the floating as well as intigers if you want to accept only decimal then use "^[0-9]+\.[0-9]+$" – NSAnant Dec 18 '15 at 12:29
  • indeed. that is why it is not clear why you recommend explicitly _not_ to use that. – holex Dec 18 '15 at 12:30