I have to detect whether a string contains any special characters. How can I check it? Does Swift support regular expressions?
var characterSet:NSCharacterSet
This answer may help the people who are using Swift 4.1
func hasSpecialCharacters() -> Bool {
do {
let regex = try NSRegularExpression(pattern: ".*[^A-Za-z0-9].*", options: .caseInsensitive)
if let _ = regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSMakeRange(0, self.count)) {
return true
}
} catch {
debugPrint(error.localizedDescription)
return false
}
return false
}
Taken reference from @Martin R's answer.