How to check if a string contains an int? -Swift
Asked Answered
T

9

33

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.

Therapeutics answered 3/8, 2015 at 15:3 Comment(3)
Convert to NSString and you can use string.containsString(otherString) and just check if it contains a number. – Hoary
Why check only for integers? Would ➽, ⨕, πŸ‚¦, or πŸ‘Ί be valid characters? – Greeson
Possible duplicate of #25652112. – Greeson
C
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.

Conceptualism answered 3/8, 2015 at 15:39 Comment(1)
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") } – Tombstone
Z
24

Simple Swift 4 version using rangeOfCharacter method from String class:

    let numbersRange = stringValue.rangeOfCharacter(from: .decimalDigits)
    let hasNumbers = (numbersRange != nil)
Zigmund answered 31/10, 2017 at 13:22 Comment(0)
H
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

Holusbolus answered 5/10, 2015 at 5:51 Comment(0)
A
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")
Androclinium answered 7/4, 2020 at 9:28 Comment(1)
While this link may answer the question, it is better to include the explanation/details of the answer here and provide justification. – Iorio
H
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")}
Haeckel answered 23/9, 2016 at 19:59 Comment(0)
B
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)}
}
Benito answered 18/8, 2016 at 9:49 Comment(0)
P
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")
Psychrometer answered 17/11, 2016 at 16:51 Comment(0)
C
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/

Circuity answered 3/8, 2015 at 15:13 Comment(2)
The question was about the Swift programming language, not about JavaScript. Btw, there are more letters than a-z, A-Z. What about Ä or é ? – Greeson
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]+$" – Pintail
L
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")
}
Lili answered 26/12, 2018 at 11:57 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.