我必须检测字符串是否包含任何特殊字符.我该怎么检查
swift是否支持正则表达式.
var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789") if (searchTerm!.rangeOfCharacterFromSet(characterSet).location == NSNotFound){ println("Could not handle special characters") }
我尝试了上面的代码,但只有当我输入第一个字符作为特殊字符时才匹配.
解决方法
你的代码检查字符串中没有字符是来自给定的集合.
你想要的是检查任何字符是否不在给定的集合中:
你想要的是检查任何字符是否不在给定的集合中:
if (searchTerm!.rangeOfCharacterFromSet(characterSet.invertedSet).location != NSNotFound){ println("Could not handle special characters") }
您也可以使用正则表达式来实现:
let regex = NSRegularExpression(pattern: ".*[^A-Za-z0-9].*",options: nil,error: nil)! if regex.firstMatchInString(searchTerm!,range: NSMakeRange(0,searchTerm!.length)) != nil { println("could not handle special characters") }
模式[^ A-Za-z0-9]匹配一个不是范围A-Z的字符,
a-z或0-9.
Swift 2的更新:
let searchTerm = "a+b" let characterset = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") if searchTerm.rangeOfCharacterFromSet(characterset.invertedSet) != nil { print("string contains special characters") }
Swift 3的更新:
let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") if searchTerm.rangeOfCharacter(from: characterset.inverted) != nil { print("string contains special characters") }