Skip to content

Instantly share code, notes, and snippets.

@jparise
Created November 15, 2012 04:34
Show Gist options
  • Save jparise/4076671 to your computer and use it in GitHub Desktop.
Save jparise/4076671 to your computer and use it in GitHub Desktop.
[NSString -substringMatchingPattern:]
- (NSString *)substringMatchingPattern:(NSString *)pattern {
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
if (regex) {
NSAssert1(regex.numberOfCaptureGroups == 1, @"Pattern must include exactly one capture group: %@", pattern);
NSTextCheckingResult *match = [regex firstMatchInString:self options:0 range:NSMakeRange(0, self.length)];
if (match && match.numberOfRanges == 2) {
return [self substringWithRange:[match rangeAtIndex:1]];
}
}
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment