// // CSRegex.m // // Created by Dag Ă…gren. // Public domain. // http://www.cocoadev.com/index.pl?CSRegex // #import "CSRegex.h" static NSString *nullstring=nil; @implementation CSRegex -(id)initWithPattern:(NSString *)pattern options:(int)options { if(self=[super init]) { int err=regcomp(&preg,[pattern UTF8String],options|REG_EXTENDED); if(err) { char errbuf[256]; regerror(err,&preg,errbuf,sizeof(errbuf)); [NSException raise:@"CSRegexException" format:@"Could not compile regex \"%@\": %s",pattern,errbuf]; } } return self; } -(void)dealloc { regfree(&preg); [super dealloc]; } -(BOOL)matchesString:(NSString *)string { if(regexec(&preg,[string UTF8String],0,NULL,0)==0) return YES; return NO; } -(NSString *)matchedSubstringOfString:(NSString *)string { const char *cstr=[string UTF8String]; regmatch_t match; if(regexec(&preg,cstr,1,&match,0)==0) { return [[[NSString alloc] initWithBytes:cstr+match.rm_so length:match.rm_eo-match.rm_so encoding:NSUTF8StringEncoding] autorelease]; } return nil; } -(NSArray *)capturedSubstringsOfString:(NSString *)string { const char *cstr=[string UTF8String]; int num=preg.re_nsub+1; regmatch_t *matches=calloc(sizeof(regmatch_t),num); if(regexec(&preg,cstr,num,matches,0)==0) { NSMutableArray *array=[NSMutableArray arrayWithCapacity:num]; int i; for(i=0;i