Check if string contains special characters in Swift

后端 未结 10 2037
时光取名叫无心
时光取名叫无心 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:45

    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.

提交回复
热议问题