4 // Created by John R Chang on 2005-11-08.
5 // This code is Creative Commons Public Domain. You may use it for any purpose whatsoever.
6 // http://creativecommons.org/licenses/publicdomain/
9 #import "NSString_RegEx.h"
13 @implementation NSString (RegEx)
15 - (NSArray *) substringsMatchingRegularExpression:(NSString *)pattern count:(int)nmatch options:(int)options ranges:(NSArray **)ranges error:(NSError **)error
17 options |= REG_EXTENDED;
23 regmatch_t * pmatch = NULL;
24 NSMutableArray * outMatches = nil;
26 // Compile the regular expression
27 errcode = regcomp(&preg, [pattern UTF8String], options);
29 goto catch_error; // regcomp error
31 // Match the regular expression against substring self
32 pmatch = calloc(sizeof(regmatch_t), nmatch+1);
33 errcode = regexec(&preg, [self UTF8String], (nmatch<0 ? 0 : nmatch+1), pmatch, 0);
35 /*if (errcode == REG_NOMATCH)
37 outMatches = [NSMutableArray array];
38 goto catch_exit; // no match
41 goto catch_error; // regexec error
45 outMatches = [NSArray arrayWithObject:self];
46 goto catch_exit; // simple match
49 // Iterate through pmatch
50 outMatches = [NSMutableArray array];
52 *ranges = [NSMutableArray array];
54 for (i=0; i<nmatch+1; i++)
56 if (pmatch[i].rm_so == -1 || pmatch[i].rm_eo == -1)
59 NSRange range = NSMakeRange(pmatch[i].rm_so, pmatch[i].rm_eo - pmatch[i].rm_so);
60 NSString * substring = [self substringWithRange:range];
61 [outMatches addObject:substring];
65 NSValue * value = [NSValue valueWithRange:range];
66 [(NSMutableArray *)*ranges addObject:value];
71 if (errcode != 0 && error)
73 // Construct error object
74 NSMutableDictionary * userInfo = [NSMutableDictionary dictionary];
76 int len = regerror(errcode, &preg, errbuf, sizeof(errbuf));
78 [userInfo setObject:[NSString stringWithUTF8String:errbuf] forKey:NSLocalizedDescriptionKey];
79 *error = [NSError errorWithDomain:@"regerror" code:errcode userInfo:userInfo];
89 - (BOOL) grep:(NSString *)pattern options:(int)options
91 NSArray * substrings = [self substringsMatchingRegularExpression:pattern count:-1 options:options ranges:NULL error:NULL];
92 return (substrings && [substrings count] > 0);