问题
I am looking for a way to compare two strings and see if the second string contains a character (letter, number, other) listed in the first, let me explain:
For example: Imagine a password with only digits and "*" are allowed:
Reference chain (1): "*0123456789" NSString
format, no NSArray
Work chain (2) = "156/15615=211" NSString
format,
How do I know that my chain 2 contains 2 characters (/=) which are not in my chain 1?
To simplify the management letters allowed, I do not want to use NSArray
to manage a chain for example a function call:
BOOL unauthorized_letter_found = check(work_chain, reference_chain);
You it must go through "for", NSPredicate
, etc. ?
PS: I'm on MAC OS, not iOS so I can not use NSRegularExpression
.
回答1:
If you want to use an NSPredicate
, you can do:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '[0-9*]+'"];
if ([predicate evaluateWithObject:@"0*2481347*"]) {
NSLog(@"passes!");
} else {
NSLog(@"fails!");
}
This is using NSPredicate
's built-in regular expression matching stuff. :)
回答2:
You could go with character sets, e.g. using -rangeOfCharacterFromSet: to check for the presence of forbidden characters:
NSCharacterSet *notAllowed = [[NSCharacterSet
characterSetWithCharactersInString:@"*0123456789"] invertedSet];
NSRange range = [inputString rangeOfCharacterFromSet:notAllowed];
BOOL unauthorized = (range.location != NSNotFound);
来源:https://stackoverflow.com/questions/5759839/checking-to-see-if-an-nsstring-contains-characters-from-a-different-nsstring