我必须检测一个字符串是否包含任何特殊字符。我该如何检查?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!, options: nil, range: NSMakeRange(0, searchTerm!.length)) != nil { println("could not handle special characters") }
该模式[^A-Za-z0-9]匹配的字符 不在 AZ,az或0-9范围内。
[^A-Za-z0-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") }