I have to detect whether a string contains any special characters. How can I check it? Does Swift support regular expressions?
var characterSet:NSCharacterSet
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
}