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 = [[[NSString alloc] initWithBytes:[self UTF8String] + range.location
62 encoding:NSUTF8StringEncoding] autorelease];
63 [outMatches addObject:substring];
67 NSValue * value = [NSValue valueWithRange:range];
68 [(NSMutableArray *)*ranges addObject:value];
73 if (errcode != 0 && error)
75 // Construct error object
76 NSMutableDictionary * userInfo = [NSMutableDictionary dictionary];
78 int len = regerror(errcode, &preg, errbuf, sizeof(errbuf));
80 [userInfo setObject:[NSString stringWithUTF8String:errbuf] forKey:NSLocalizedDescriptionKey];
81 *error = [NSError errorWithDomain:@"regerror" code:errcode userInfo:userInfo];
91 - (BOOL) grep:(NSString *)pattern options:(int)options
93 NSArray * substrings = [self substringsMatchingRegularExpression:pattern count:-1 options:options ranges:NULL error:NULL];
94 return (substrings && [substrings count] > 0);