检查字符串是否包含Swift中的特殊字符 [英] Check if string contains special characters in Swift
问题描述
我必须检测字符串是否包含任何特殊字符。我怎么检查呢? Swift是否支持正则表达式?
I have to detect whether a string contains any special characters. How can I check it? Does Swift support regular expressions?
var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789")
if (searchTerm!.rangeOfCharacterFromSet(characterSet).location == NSNotFound){
println("Could not handle special characters")
}
我尝试了上面的代码,但只有当我输入第一个字符作为特殊字符时它才匹配。
I tried the code above, but it matches only if I enter the first character as a special character.
推荐答案
您的代码检查字符串中的字符是否来自给定集合。
您想要检查给定集合中
Your code check if no character in the string is from the given set. What you want is to check if any character is not in the given set:
if (searchTerm!.rangeOfCharacterFromSet(characterSet.invertedSet).location != NSNotFound){
println("Could not handle special characters")
}
您也可以使用正则表达式实现此目的:
You can also achieve this using regular expressions:
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中不的字符。
The pattern [^A-Za-z0-9]
matches a character which is not from the ranges A-Z,
a-z, or 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")
}
这篇关于检查字符串是否包含Swift中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!