如何检查字符串是否包含int? -迅速

时间:2015-08-03 15:03:49

标签: string swift keyboard int contains

我需要知道字符串是否包含Int,以确保用户输入的名称是有效的全名, 为此,我需要使用户只键入字符,或者有效的是用户输入的字符串中没有整数。 谢谢你的帮助。

9 个答案:

答案 0 :(得分:32)

您可以将基础方法与Swift字符串一起使用,这就是您应该在此处执行的操作。 NSString内置了一些方法,使用NSCharacterSet来检查是否存在某些类型的字符。这很好地转换为Swift:

var str = "Hello, playground1"

let decimalCharacters = CharacterSet.decimalDigits

let decimalRange = str.rangeOfCharacter(from: decimalCharacters)

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

如果您对限制可输入内容感兴趣,则应实施UITextFieldDelegate和方法textField(_:shouldChangeCharactersIn:replacementString:),以防止人们首先输入这些字符。

答案 1 :(得分:9)

使用rangeOfCharacter类中的String方法的简单 Swift 4 版本:

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

答案 2 :(得分:5)

此方法现在用于检查字符串是否包含数字

func doStringContainsNumber( _string : String) -> Bool{

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

        return containsNumber
        }

如果您的字符串包含数字,则返回true,否则返回false。希望它有所帮助

答案 3 :(得分:4)

//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")

答案 4 :(得分:3)

        //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")}

答案 5 :(得分: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)}
}

答案 6 :(得分:1)

Swift 2.3。版本工作。

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

用法:

//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")

答案 7 :(得分:0)

你需要通过包装其nsRegularExpression

来欺骗Swift使用Regex
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")
}

我从http://benscheirman.com/2014/06/regex-in-swift/

获得了这些内容

答案 8 :(得分: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")
}