Regular expressions (regex) are a powerful way to see if a string matches a given pattern. For example, the following regular expression can be used to match a social security number:
(\d{3})-(\d{2})-(\d{4})
There are various frameworks out there (such as RegexKit) that implement regular expression support for Cocoa, but they do a lot more than just matching. They also do replacing, iterating, and so on. If all you're looking for is just a match, the following NSString category will work just fine:
//NSString+RegExpExtensions.h @interface NSString (RegExpExtensions) - (BOOL)doesMatchRegStringExp:(NSString *)string; @end
//NSString+RegExpExtensions.m @implementation NSString (RegExpExtensions) - (BOOL)doesMatchRegStringExp:(NSString *)string { NSPredicate *regExpPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", string]; return [regExpPredicate evaluateWithObject:self]; } @end
That means you can now do simple matching like so:
NSString * pattern = @"(\\d{3})-(\\d{2})-(\\d{4})"; NSString * testString = @"123-45-6789"; if ([testString doesMatchRegStringExp:pattern]) { NSLog(@"It's a match!"); }
This code, if run, will log "It's a match!". Notice that when using special patterns (for example "\d", to mean all numerical digits), they need to be double escaped!
Via:
http://riquedafreak.blogspot.com/2007/12/building-regular-expressions-in...
http://www.stiefels.net/2007/01/24/regular-expressions-for-nsstring/