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
Use
NSPredicate
withString
extension.Usage
You are quite close
You can create a set of characters and check if it is a superset of your string. It is much faster than using regex.