Search code examples
regexios5nsregularexpression

IOS5 NSRegularExpression can't parse very basic expression


I want to parse items=14-35 with regex to 14 and 35

I use /^items=([-\d,]+)$/ in PHP and want to use it in an iPhone project. I checked Apple's documentation and similar questions here like NSRegularExpression .

NSError *error = nil;
NSRegularExpression *regex = 
 [NSRegularExpression regularExpressionWithPattern:@"/^items=([-\\d,]+)$/"
                 options:NSRegularExpressionCaseInsensitive error:&error];

NSString *str = @"items=14-35";
NSTextCheckingResult *match = 
  [regex firstMatchInString:str 
         options:NSMatchingAnchored 
         range:NSMakeRange(0, [str length])];

NSLog(@"MATCH : %@",match);

The above code outputs NULL and match.numberOfRanges = 0 without any error.


Solution

  • The delimiter slashes at the beginning and end aren't part of the regular expression. Remove them from the pattern string.

    (Sometimes, slashes are used to delimit the regular expression from flags at the end, but Cocoa doesn't do that. Since you pass the flags explicitly, there's no need for the slashes.)