skip to Main Content

In Swift, I have a String Variable thisString. I want to check to make sure the string contains only letters, numbers and/or dashes (-). Aside from doing this:

if ( thisString.contains("$") || thisString.contains("%") ) {
  //reject
} else {
 //accept
}

for each undesired character, which is ridiculous, I cant figure it out..

I would like to, in theory, do something like this with a regular expression:

if ( thisString.contains(regex([^a-zA-Z0-9-]) ) { 
  //reject
} else {
  //accept
}

Is this possible?

Thank you!

3

Answers


  1. Use NSPredicate with String extension.

    extension String {
        enum ValidationType: String {
            case alphabet = "[A-Za-z]+"
            case alphabetWithSpace = "[A-Za-z ]*"
            case alphabetNum = "[A-Za-z-0-9]*"
            case alphabetNumWithDash = "[A-Za-z-0-9-]*"
        }
        
        func isValid(_ type: ValidationType) -> Bool {
            guard !isEmpty else { return false }
            let regTest = NSPredicate(format: "SELF MATCHES %@", type.rawValue)
            return regTest.evaluate(with: self)
        }
    }
    

    Usage

    thisString.isValid(.alphabetNumWithDash)
    
    Login or Signup to reply.
  2. You are quite close

    if thisString.range(of: "[^a-zA-Z0-9-]", options: .regularExpression) != nil { 
      //reject
    } else {
      //accept
    }
    
    Login or Signup to reply.
  3. You can create a set of characters and check if it is a superset of your string. It is much faster than using regex.

    let validCharacters: Set = .init("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-")
    
    let string1 = "Lkabo-1"
    let string2 = "Lkabo-2!"
    
    if validCharacters.isSuperset(of: string1) {
        print(true)  // true
    } else {
        print(false)
    }
    if validCharacters.isSuperset(of: string2) {
        print(true)
    } else {
        print(false)  // false
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search