| 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
|
#import "NSString+Regex.h"
#include <regex.h>
@implementation NSString (Regex)
static void raise_reg_error_exception(const char* name, int errorcode, regex_t* regex) {
NSMutableData* errorString = [NSMutableData data];
[errorString setLength:regerror(errorcode, regex, NULL, 0)];
size_t errorSize = regerror(errorcode, regex, [errorString mutableBytes], [errorString length]);
regfree(regex);
NSCAssert2(errorSize == [errorString length],
@"Unexpected size in raise_reg_error_exception: %d, %d",
errorSize, [errorString length]);
[NSException raise: NSInvalidArgumentException
format: @"%s: %s", name, [errorString bytes]];
}
- (NSArray *) findRegularExpression:(NSString *)re ignoreCase:(BOOL)ignoreCase; {
regex_t regex;
int regCompFlags = REG_EXTENDED;
int regExecFlags = 0;
int err = 0;
if (ignoreCase)
{
regCompFlags |= REG_ICASE;
}
if ((err = regcomp(®ex, [re UTF8String], regCompFlags)) != 0)
{
raise_reg_error_exception("regcomp", err, ®ex);
return nil;
}
NSMutableData* matchData = [NSMutableData dataWithCapacity: (1 + regex.re_nsub) * sizeof (regmatch_t)];
regmatch_t* matches = [matchData mutableBytes];
if ((err = regexec(®ex, [self UTF8String], 1 + regex.re_nsub, matches, regExecFlags)) != 0)
{
if (err != REG_NOMATCH)
{
raise_reg_error_exception("regexec", err, ®ex);
}
regfree(®ex);
return nil;
}
NSMutableArray *matchArray = [NSMutableArray arrayWithCapacity: 1 + regex.re_nsub];
int m;
for (m = 0; m <= regex.re_nsub; m++)
{
if (matches[m].rm_so == -1)
{
[matchArray addObject: [NSNull null]];
}
else
{
NSRange matchRange = NSMakeRange(matches[m].rm_so, (matches[m].rm_eo - matches[m].rm_so));
[matchArray addObject:[self substringWithRange:matchRange]];
}
}
regfree(®ex);
return matchArray;
}
@end
|