I have to detect whether a string contains any special characters. How can I check it? Does Swift support regular expressions?
var characterSet:NSCharacterSet
Mahendra's answer can be stripped down a bit by using an inversion(^) within the regex clause. Additionally, you don't need A-Z and a-z when using the caseInsensitive option, as Swift covers that eventuality for you:
extension String {
func containsSpecialCharacters(string: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: "[^a-z0-9 ]", options: .caseInsensitive)
if let _ = regex.firstMatch(in: string, options: [], range: NSMakeRange(0, string.count)) {
return true
} else {
return false
}
} catch {
debugPrint(error.localizedDescription)
return true
}
}