-
Notifications
You must be signed in to change notification settings - Fork 601
/
NSString_RegEx.m
97 lines (81 loc) · 2.56 KB
/
NSString_RegEx.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//
// NSString_RegEx.m
//
// Created by John R Chang on 2005-11-08.
// This code is Creative Commons Public Domain. You may use it for any purpose whatsoever.
// http://creativecommons.org/licenses/publicdomain/
//
#import "NSString_RegEx.h"
#include <regex.h>
@implementation NSString (RegEx)
- (NSArray *) substringsMatchingRegularExpression:(NSString *)pattern count:(int)nmatch options:(int)options ranges:(NSArray **)ranges error:(NSError **)error
{
options |= REG_EXTENDED;
if (error)
*error = nil;
int errcode = 0;
regex_t preg;
regmatch_t * pmatch = NULL;
NSMutableArray * outMatches = nil;
// Compile the regular expression
errcode = regcomp(&preg, [pattern UTF8String], options);
if (errcode != 0)
goto catch_error; // regcomp error
// Match the regular expression against substring self
pmatch = calloc(sizeof(regmatch_t), nmatch+1);
errcode = regexec(&preg, [self UTF8String], (nmatch<0 ? 0 : nmatch+1), pmatch, 0);
/*if (errcode == REG_NOMATCH)
{
outMatches = [NSMutableArray array];
goto catch_exit; // no match
}*/
if (errcode != 0)
goto catch_error; // regexec error
if (nmatch == -1)
{
outMatches = [NSArray arrayWithObject:self];
goto catch_exit; // simple match
}
// Iterate through pmatch
outMatches = [NSMutableArray array];
if (ranges)
*ranges = [NSMutableArray array];
int i;
for (i=0; i<nmatch+1; i++)
{
if (pmatch[i].rm_so == -1 || pmatch[i].rm_eo == -1)
break;
NSRange range = NSMakeRange(pmatch[i].rm_so, pmatch[i].rm_eo - pmatch[i].rm_so);
NSString * substring = [[[NSString alloc] initWithBytes:[self UTF8String] + range.location
length:range.length
encoding:NSUTF8StringEncoding] autorelease];
[outMatches addObject:substring];
if (ranges)
{
NSValue * value = [NSValue valueWithRange:range];
[(NSMutableArray *)*ranges addObject:value];
}
}
catch_error:
if (errcode != 0 && error)
{
// Construct error object
NSMutableDictionary * userInfo = [NSMutableDictionary dictionary];
char errbuf[256];
int len = regerror(errcode, &preg, errbuf, sizeof(errbuf));
if (len > 0)
[userInfo setObject:[NSString stringWithUTF8String:errbuf] forKey:NSLocalizedDescriptionKey];
*error = [NSError errorWithDomain:@"regerror" code:errcode userInfo:userInfo];
}
catch_exit:
if (pmatch)
free(pmatch);
regfree(&preg);
return outMatches;
}
- (BOOL) grep:(NSString *)pattern options:(int)options
{
NSArray * substrings = [self substringsMatchingRegularExpression:pattern count:-1 options:options ranges:NULL error:NULL];
return (substrings && [substrings count] > 0);
}
@end