Popular Tags

Who's online

There are currently 0 users and 69 guests online.

User login

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:

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:

@interface NSString (RegExpExtensions)
- (BOOL)doesMatchRegStringExp:(NSString *)string;

@implementation NSString (RegExpExtensions)
- (BOOL)doesMatchRegStringExp:(NSString *)string {
    NSPredicate *regExpPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", string];
    return [regExpPredicate evaluateWithObject:self];

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!


Your rating: None Average: 4 (5 votes)



The site has recently been updated. You may notice some of the following issues:

  • Some URLs no longer work. Please use the search box.
  • File uploads should now be working. If you experience problems, please contact us.