您好我想检查用户是否输入包含字符集之外的任何内容的字符串(包含我的集合中未指定的字符):
“abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 _-。”
我怎样才能做到这一点?提前谢谢!
更新
我尝试使用
var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789")
if (searchTerm!.rangeOfCharacterFromSet(characterSet.invertedSet).location == NSNotFound){
println("No special characters")
}
但我得到的是'范围'?没有会员'位置'错误
答案 0 :(得分:2)
您可以使用自定义NSCharacterSet charactersInString并检查字符类型是否为该invertSet的成员:
extension NSCharacterSet {
func characterInStringIsMember(aString: String) -> Bool {
var result = false
aString
.characters
.map{ UInt16(String($0).unicodeScalars.first?.value ?? 0) }
.forEach { result = characterIsMember($0) }
return result
}
}
let customCharSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-.").invertedSet
let stringTest = "abc"
if customCharSet.characterInStringIsMember(stringTest) {
print(true) //
} else {
print(false) // "false\n"
}
let stringTest2 = "abc%"
if customCharSet.characterInStringIsMember(stringTest2) {
print(true) // "true\n"
} else {
print(false)
}
答案 1 :(得分:0)
这是一个简单的解决方案,只需使用NSCharacterSet: -
let name1="myname" // Input
let characterSet: NSMutableCharacterSet = NSMutableCharacterSet.alphanumericCharacterSet()
characterSet.addCharactersInString("_-.")
name1.stringByTrimmingCharactersInSet(characterSet).isEmpty // If this return true, you enetered the right charcters