Objective-C and Cocoa

Navigation

Recent site activity

Home‎ > ‎

NSPredicate examples

http://developer.apple.com/documentation/Cocoa/Conceptual/Predicates/predicates.html

Predicate format strings

http://developer.apple.com/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html


ICU Regular Expression information

http://www.icu-project.org/userguide/regexp.html

Examples

http://theocacao.com/document.page/346

The following code is from a GTMUnitTestCase for an iPhone application that I've been working on.  The first method is a convenience method for building and evaluating the predicate with the input string and regular expression string.  The second method is a test case.

- (BOOL)assertRegex:(NSString*)stringToSearch withRegex:(NSString*)regexString {
    NSPredicate *regex = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexString];
    return [regex evaluateWithObject:stringToSearch];   
}

- (void)testRegexes {
    // Find a string at the end of a line.
    STAssertTrue([self assertRegex:@"Christopher Bartling"
                         withRegex:@".*Bartling$"], @"Regex did not match.");
   
    // Find a string at the beginning of a line.
    STAssertTrue([self assertRegex:@"Christopher Bartling"
                         withRegex:@"^Chris.*"], @"Regex did not match.");
   
    // Find a sequence of 3 characters in succession using an interval quantifier (e.g {3,3}).
    STAssertTrue([self assertRegex:@"**** = *** === ****** == *****"
                         withRegex:@".*={3,3}.*"], @"Regex did not match.");
}