Created
May 14, 2012 21:26
-
-
Save batosai/2697274 to your computer and use it in GitHub Desktop.
Get NSArray matches with NSRegularExpression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSRegularExpression (regularExpression) | |
- (NSArray*) matchWithString:(NSString*)data; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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