One of the problems with \w
is that you need to get it into a string with all the backslashes properly escaped.
NSArray *names = @[@"Cortázar, J", @"Król, S", @"Don't Match This", @"Doe, J", @"Høegh, K"];
NSString *pattern = @"\\w+, \\w";
NSPredicate *pred = [NSPredicate predicateWithFormat: @"self MATCHES %@", pattern];
NSArray* result = [names filteredArrayUsingPredicate: pred];
It correctly matches the names, but leaves out the "wrong" string at index 2.
This shows that you can match the strings with an NSRegularExpression
as the predicate engine uses the same regular expression syntax.
Edited to add:
If you insist on using an NSRegularExpression
directly, then you can see it work with a little more code:
// The names and pattern variables taken from code above
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:&error];
for (NSString *string in names) {
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
NSString *result = [string substringWithRange:rangeOfFirstMatch];
NSLog(@"Match: '%@'", result);
}
else {
NSLog(@"No match: '%@'", string);
}
}
You will see that it matches the names, with either pure ASCII or various European accented characters, but it does not match the string "Don't Match This".