Check if a String is alphanumeric in Swift

早过忘川 提交于 2019-12-03 14:30:14

问题


In Swift, how can I check if a String is alphanumeric, ie, if it contains only one or more alphanumeric characters [a-zA-Z0-9], excluding letters with diacritics, eg, é.


回答1:


extension String {
    var isAlphanumeric: Bool {
        return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
    }
}

"".isAlphanumeric        // false
"abc".isAlphanumeric     // true
"123".isAlphanumeric     // true
"ABC123".isAlphanumeric  // true
"iOS 9".isAlphanumeric   // false



回答2:


A modern Swift 3 and 4 solution

extension String {

    func isAlphanumeric() -> Bool {
        return self.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) == nil && self != ""
    }

    func isAlphanumeric(ignoreDiacritics: Bool = false) -> Bool {
        if ignoreDiacritics {
            return self.range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil && self != ""
        }
        else {
            return self.isAlphanumeric()
        }
    }

}

Usage:

"".isAlphanumeric()         == false
"Hello".isAlphanumeric()    == true
"Hello 2".isAlphanumeric()  == false
"Hello3".isAlphanumeric()   == true

"Français".isAlphanumeric() == true
"Français".isAlphanumeric(ignoreDiacritics: true) == false

This works with languages other than English, allowing diacritic characters like è and á, etc. If you'd like to ignore these, use the flag "ignoreDiacritics: true".




回答3:


I felt the accepted answer using regex was concrete but a rather heavy solution. You could check it this way also in Swift 3.0:

if yourString.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) != nil {
    return "Username can only contain numbers or digits"
}



回答4:


extension String {
    /// Allows only `a-zA-Z0-9`
    public var isAlphanumeric: Bool {
        guard !isEmpty else {
            return false
        }
        let allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
        let characterSet = CharacterSet(charactersIn: allowed)
        guard rangeOfCharacter(from: characterSet.inverted) == nil else {
            return false
        }
        return true
    }
}

XCTAssertFalse("".isAlphanumeric)
XCTAssertFalse("climate change".isAlphanumeric)
XCTAssertFalse("Poüet".isAlphanumeric)
XCTAssertTrue("Hawking2018".isAlphanumeric)



回答5:


This regex used to check that string contains atleast 1 alphabet + atleast 1 digit alongwith 8 characters.

"^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"


来源:https://stackoverflow.com/questions/35992800/check-if-a-string-is-alphanumeric-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!