Check if a String is alphanumeric in Swift

Deadly 提交于 2019-12-03 04:19:16
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

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".

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"
}
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)
Sarishti batta

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