Skip to content

Instantly share code, notes, and snippets.

@Koze
Last active August 29, 2015 14:19
Show Gist options
  • Save Koze/aec21e9ca3627c410ab9 to your computer and use it in GitHub Desktop.
Save Koze/aec21e9ca3627c410ab9 to your computer and use it in GitHub Desktop.
NSPredicate with regular expression
- (void)testRegularExpression
{
// \d+ regular expression pattern
// \\d+ pattern with escape for string
// \\\\d+ pattern with re-escape for predicate format
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '\\d+'"];
NSLog(@"%@", predicate);
// SELF MATCHES "d+"
predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '\\\\d+'"];
NSLog(@"%@", predicate);
// SELF MATCHES "\\d+"
predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"\\d+"];
NSLog(@"%@", predicate);
// SELF MATCHES "\\d+"
BOOL result = NO;
result = [predicate evaluateWithObject:@"123abc"];
NSLog(@"%d", result);
// 0
result = [predicate evaluateWithObject:@"123456"];
NSLog(@"%d", result);
// 1
result = [predicate evaluateWithObject:@"abcdef"];
NSLog(@"%d", result);
// 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment