Check if string contains special characters in Swift

后端 未结 10 2023
时光取名叫无心
时光取名叫无心 2020-12-12 18:20

I have to detect whether a string contains any special characters. How can I check it? Does Swift support regular expressions?

var characterSet:NSCharacterSet         


        
相关标签:
10条回答
  • 2020-12-12 18:53

    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")
    
    }
    

    The pattern [^A-Za-z0-9] matches a character which is not from the ranges A-Z, a-z, or 0-9.

    Update for Swift 2:

    let searchTerm = "a+b"
    
    let characterset = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    if searchTerm.rangeOfCharacterFromSet(characterset.invertedSet) != nil {
        print("string contains special characters")
    }
    

    Update for Swift 3:

    let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    if searchTerm.rangeOfCharacter(from: characterset.inverted) != nil {
        print("string contains special characters")
    }
    
    0 讨论(0)
  • 2020-12-12 18:53

    Inverting your character set will work, because in your character set you have all the valid characters:

    var characterSet:NSCharacterSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    if (searchTerm!.rangeOfCharacterFromSet(characterSet.invertedSet).location == NSNotFound){
        println("No special characters")
    }
    

    Hope this helps.. :)

    0 讨论(0)
  • 2020-12-12 18:55

    Depending on the definition of special characters, you could use this:

    let chars =  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    
    chars.canBeConvertedToEncoding(NSASCIIStringEncoding)
    
    0 讨论(0)
  • 2020-12-12 19:01

    @Martin R answer is great, I just wanted to update it (the second part) to Swift 2.1 version

    let regex = try! NSRegularExpression(pattern: ".*[^A-Za-z0-9].*", options: NSRegularExpressionOptions())
    if regex.firstMatchInString(searchTerm!, options: NSMatchingOptions(), range:NSMakeRange(0, searchTerm!.characters.count)) != nil {
        print("could not handle special characters")
    }
    

    I used try! as we can be sure it create a regex, it doesn't base on any dynamic kind of a data

    0 讨论(0)
提交回复
热议问题