To check if a string contains only alphabets and numbers in Swift, you can use regular expressions from the NSRegularExpression
class.
In this example,
Foundation
framework to use regular expressions.NSRegularExpression
class to create a regular expression object with the pattern.matches
method of the regular expression to check if the string matches the pattern.containsOnlyAlphabetsAndNumbers
will be true
, otherwise false
.import Foundation
let str = "Hello123"
let pattern = "^[a-zA-Z0-9]+$"
let regex = try! NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: str, range: NSRange(str.startIndex..., in: str))
let containsOnlyAlphabetsAndNumbers = !matches.isEmpty
print("String contains only alphabets and numbers:", containsOnlyAlphabetsAndNumbers)
String contains only alphabets and numbers: true
In this tutorial, we learned How to Check if String contains only Alphabets and Numbers in Swift language with well detailed examples.