31

I need to know if a string contains an Int to be sure that a name the user entered is a valid full name, for that I need to either make the user type only chars, or valid that there are no ints in the string the user entered. Thanks for all the help.

arbel03
  • 1,217
  • 2
  • 14
  • 24
  • Convert to `NSString` and you can use `string.containsString(otherString)` and just check if it contains a number. – Kendel Aug 03 '15 at 15:09
  • 1
    Why check only for integers? Would ➽, ⨕, , or be valid characters? – Martin R Aug 03 '15 at 15:11
  • Possible duplicate of http://stackoverflow.com/questions/25651612/how-do-i-check-uitextfield-values-for-specific-types-of-characters-e-g-letters. – Martin R Aug 03 '15 at 15:20

9 Answers9

58

You can use Foundation methods with Swift strings, and that's what you should do here. NSString has built in methods that use NSCharacterSet to check if certain types of characters are present. This translates nicely to Swift:

var str = "Hello, playground1"

let decimalCharacters = CharacterSet.decimalDigits

let decimalRange = str.rangeOfCharacter(from: decimalCharacters)

if decimalRange != nil {
    print("Numbers found")
}

If you're interested in restricting what can be typed, you should implement UITextFieldDelegate and the method textField(_:shouldChangeCharactersIn:replacementString:) to prevent people from typing those characters in the first place.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • Swift 3, let str = "Hello, playground1" let decimalCharacters = NSCharacterSet.decimalDigits let decimalRange = str.rangeOfCharacter(from: decimalCharacters, options: String.CompareOptions.literal, range: nil) if decimalRange != nil { print("Numbers found") } – Jeff Jan 04 '17 at 18:43
23

Simple Swift 4 version using rangeOfCharacter method from String class:

    let numbersRange = stringValue.rangeOfCharacter(from: .decimalDigits)
    let hasNumbers = (numbersRange != nil)
8

This method is what i use now for checking if a string contains a number

func doStringContainsNumber( _string : String) -> Bool{

        let numberRegEx  = ".*[0-9]+.*"
        let testCase = NSPredicate(format:"SELF MATCHES %@", numberRegEx)
        let containsNumber = testCase.evaluateWithObject(_string)

        return containsNumber
        }

If your string Contains a number it will return true else false. Hope it helps

Joker
  • 830
  • 2
  • 14
  • 30
5
//A function that checks if a string has any numbers
func stringHasNumber(_ string:String) -> Bool {
    for character in string{
        if character.isNumber{
            return true
        }
    }
    return false
}

/// Check stringHasNumber function
stringHasNumber("mhhhldiddld")
stringHasNumber("kjkdjd99900")
Mostafa Lotfy
  • 51
  • 1
  • 3
  • While this link may answer the question, it is better to include the explanation/details of the answer here and provide justification. – Mebin Joe Apr 07 '20 at 10:29
4
        //Swift 3.0 to check if String contains numbers (decimal digits):


    let someString = "string 1"
    let numberCharacters = NSCharacterSet.decimalDigits

    if someString.rangeOfCharacter(from: numberCharacters) != nil
    { print("String contains numbers")}
    else if someString.rangeOfCharacter(from: numberCharacters) == nil
    { print("String doesn't contains numbers")}
Lukasz D
  • 241
  • 4
  • 8
1
if (ContainsNumbers(str).count > 0)
{
    // Your string contains at least one number 0-9
}

func ContainsNumbers(s: String) -> [Character]
{
    return s.characters.filter { ("0"..."9").contains($0)}
}
Miika Pakarinen
  • 261
  • 1
  • 4
  • 5
1

Swift 2.3. version working.

extension String
{
    func containsNumbers() -> Bool
    {
        let numberRegEx  = ".*[0-9]+.*"
        let testCase     = NSPredicate(format:"SELF MATCHES %@", numberRegEx)
        return testCase.evaluateWithObject(self)
    }
}

Usage:

//guard let firstname = textField.text else { return }
    let testStr1 = "lalalala"
    let testStr2 = "1lalalala"
    let testStr3 = "lal2lsd2l"

    print("Test 1 = \(testStr1.containsNumbers())\nTest 2 = \(testStr2.containsNumbers())\nTest 3 = \(testStr3.containsNumbers())\n")
Darkwonder
  • 1,149
  • 1
  • 13
  • 26
0

You need to trick Swift into using Regex by wrapping up its nsRegularExpression

class Regex {
  let internalExpression: NSRegularExpression
  let pattern: String

  init(_ pattern: String) {
    self.pattern = pattern
    var error: NSError?
    self.internalExpression = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error)
  }

  func test(input: String) -> Bool {
    let matches = self.internalExpression.matchesInString(input, options: nil, range:NSMakeRange(0, countElements(input)))
    return matches.count > 0
  }

}

if Regex("\\d/").test("John 2 Smith") {
  println("has a number in the name")
}

I got these from http://benscheirman.com/2014/06/regex-in-swift/

Clay Sills
  • 235
  • 1
  • 9
  • The question was about the *Swift* programming language, not about JavaScript. Btw, there are more letters than a-z, A-Z. What about Ä or é ? – Martin R Aug 03 '15 at 15:15
  • While this answers the question of locating digits in a string, perhaps it might be better to check if all characters in the string are valid (i.e., word chars or spaces) using the regex "^[\\w\\s]+$" – David Berry Aug 03 '15 at 15:31
0
let numericCharSet = CharacterSet.init(charactersIn: "1234567890")

let newCharSet = CharacterSet.init(charactersIn: "~`@#$%^&*(){}[]<>?")

let sentence = "Tes#ting4 @Charact2er1Seqt"

if sentence.rangeOfCharacter(from: numericCharSet) != nil {
    print("Yes It,Have a Numeric")
    let removedSpl = sentence.components(separatedBy: newCharSet).joined()
    print(sentence.components(separatedBy: newCharSet).joined())
    print(removedSpl.components(separatedBy: numericCharSet).joined())
} 

else {
    print("No")
}
Revanth Kausikan
  • 673
  • 1
  • 9
  • 21