Skip to content

Instantly share code, notes, and snippets.

@michaeleisel
Created February 11, 2014 00:31
Show Gist options
  • Save michaeleisel/8927113 to your computer and use it in GitHub Desktop.
Save michaeleisel/8927113 to your computer and use it in GitHub Desktop.
-(NSArray*)objectForKeyedSubscript:(NSString*)pattern
{
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSAssert( ! error, @"regex processing error");
NSMutableArray *strings = [NSMutableArray new];
NSArray *matches = [regex matchesInString:self options:0 range:self.fullRange];
for(NSTextCheckingResult *match in matches) {
for (NSInteger i = 0; i < match.numberOfRanges; i++) {
NSRange range = [match rangeAtIndex: i];
NSString *substring = [self substringWithRange: range];
[strings addObject: substring];
}
}
return strings.count == 0 ? nil : strings;
}
-(id)setObject:(NSString*)newPattern forKeyedSubscript:(NSString*)oldPattern
{
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:oldPattern options:0 error:&error];
NSAssert(! error, @"Regex processing error");
NSString *newString = [regex stringByReplacingMatchesInString:self options:0 range:self.fullRange withTemplate: newPattern];
return newString;
}
@michaeleisel
Copy link
Author

dope

@eimantas
Copy link

One of the most creative ways to use subscript on strings .)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment