Skip to content

Instantly share code, notes, and snippets.

@batosai
Created May 14, 2012 21:26
Show Gist options
  • Save batosai/2697274 to your computer and use it in GitHub Desktop.
Save batosai/2697274 to your computer and use it in GitHub Desktop.
Get NSArray matches with NSRegularExpression
//Sample
NSError *error = nil;
NSString *pattern = @"!.*!";
NSString *data = @"Lorem ipsum !dolor! sit amet, consectetur !adipisicing! elit";
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive error:&error];
NSArray * matches = [regex matchWithString:data];
NSLog(@"%@", matches);
#import <Foundation/Foundation.h>
@interface NSRegularExpression (regularExpression)
- (NSArray*) matchWithString:(NSString*)data;
@end
#import "NSRegularExpression.h"
@implementation NSRegularExpression (regularExpression)
- (NSArray*) matchWithString:(NSString*)data
{
NSMutableArray *results = [NSMutableArray array];
NSArray *matches = [self matchesInString:data
options:0
range:NSMakeRange(0, [data length])];
for (NSTextCheckingResult *match in matches) {
NSMutableArray *result = [NSMutableArray array];
NSRange matchRange = [match range];
NSString *numString = [data substringWithRange:matchRange];
[result addObject:numString];
for (int i=1;i < (int)match.numberOfRanges;i++) {
NSRange range = [match rangeAtIndex:i];
@try {
NSString *numString = [data substringWithRange:range];
[result addObject:numString];
}
@catch (NSException *exception) {
[result addObject:[NSNull null]];
}
}
[results addObject:result];
}
return [results count] > 1 ? results : [results objectAtIndex:0] ;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment