Check if string contains special characters in Swift

后端 未结 10 2031
时光取名叫无心
时光取名叫无心 2020-12-12 18:20

I have to detect whether a string contains any special characters. How can I check it? Does Swift support regular expressions?

var characterSet:NSCharacterSet         


        
10条回答
  •  再見小時候
    2020-12-12 18:48

    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
            }
        }

提交回复
热议问题