Search code examples
swift

Use regular expression in Swift String.contains() func


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 can't 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?


Solution

  • You are quite close

    if thisString.range(of: "[^a-zA-Z0-9-]", options: .regularExpression) != nil { 
      //reject
    } else {
      //accept
    }
    

    Update:

    It becomes much more convenient with the new Swift Regex syntax (available in Swift 5.7+) where the syntax is pretty close to what you are looking for

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