Check if string contains special characters in Swift

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

    For the purpose of filename sanitization, I prefer to detect the invalid characters, rather than provide an allowed character set. After all, many non-English speaking users need accented characters. The following function is inspired by this gist:

    func checkForIllegalCharacters(string: String) -> Bool {
        let invalidCharacters = CharacterSet(charactersIn: "\\/:*?\"<>|")
        .union(.newlines)
        .union(.illegalCharacters)
        .union(.controlCharacters)
    
        if string.rangeOfCharacter(from: invalidCharacters) != nil {
            print ("Illegal characters detected in file name")
            // Raise an alert here
            return true
        } else {
        return false
    }
    

提交回复
热议问题