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, é.
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, é.
Checking if a string contains a substring in Swift is very easy. Strings in Swift have a built in method called contains . This method with allow us to check if a string contains a given substring.
Substrings. When you get a substring from a string—for example, using a subscript or a method like prefix(_:) —the result is an instance of Substring , not another string. Substrings in Swift have most of the same methods as strings, which means you can work with substrings the same way you work with strings.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With