Check if NSString contains alphanumeric + underscore characters only

后端 未结 7 1874
余生分开走
余生分开走 2021-01-30 00:52

I\'ve got a string that needs to be only a-z, 0-9 and _

How do I check if the input is valid? I\'ve tried this but it accepts letter like å,ä,ö,ø etc.

NS         


        
7条回答
  •  野性不改
    2021-01-30 01:23

    Here's how you can do it in Swift (as an extension of the String class):

    extension String {
    
         func containsValidCharacters() -> Bool {
    
            var charSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_")
            charSet = charSet.invertedSet
    
            let range = (self as NSString).rangeOfCharacterFromSet(charSet)
    
            if range.location != NSNotFound {
                return false
            }
    
            return true
        }
    }
    

提交回复
热议问题