views:

546

answers:

2

I'm having problems with simple NSPredicates and regular expressions:

NSString *mystring = @"file://questions/123456789/desc-text-here";
NSString *regex = @"file://questions+";

NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isMatch = [regextest evaluateWithObject:mystring];

In the above example isMatch is is always false/NO.

What am I missing? I can't seem to find a regular expression that will match file://questions.

+3  A: 

NSPredicates seem to try and match the entire string, not just a substring. Your trailing + simply means to match one or more 's' characters. You need to allow a match for any trailing characters. This works: regex = @"file://questions.*"

Matt B.
+3  A: 

If you're just trying to test whether the string exists: try this

NSString *myString = @"file://questions/123456789/desc-text-here";
NSString *searchString = @"file://questions";

NSRange resultRange = [myString rangeWithString:searchString];
BOOL result = resultRange.location != NSNotFound;

Alteratively, using predicates

NSString *myString = @"file://questions/123456789/desc-text-here";
NSString *searchString = @"file://questions";

NSPredicate *testPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", searchString];

BOOL result = [testPredicate evaluateWithObject:myString];

I believe that the documentation states that using a predicate is the way to go when just checking to see if a substring exists.

Abizern
Or `hasPrefix:` for the begins-with case. And there are predicate operators for both of these (and ends-with), which one may prefer if they do not need a regular expression. http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html
Peter Hosey