forked from RPGillespie6/posix-regex-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPOSIXRegex.cpp
154 lines (118 loc) · 2.64 KB
/
POSIXRegex.cpp
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#include "POSIXRegex.h"
using namespace std;
using namespace POSIX;
////////////////////// Start Match Implementations //////////////////////
Match::Match()
{
match = "";
}
Match::Match(string match)
{
this->match = match;
}
int Match::start(unsigned int group)
{
if (group >= pgroups.size())
return -1;
return pgroups[group].start;
}
int Match::end(unsigned int group)
{
if (group >= pgroups.size())
return -1;
return pgroups[group].end;
}
string Match::group(unsigned int group)
{
if (group >= pgroups.size())
return "";
if (pgroups[group].start == -1 || pgroups[group].end == -1)
return "";
return match.substr(pgroups[group].start, pgroups[group].end - pgroups[group].start);
}
vector<string> Match::groups()
{
vector<string> g;
for (unsigned int i = 0; i < pgroups.size(); i++)
{
if (pgroups[i].start >= 0 && pgroups[i].end >= 0)
g.push_back(match.substr(pgroups[i].start, pgroups[i].end - pgroups[i].start));
}
return g;
}
int Match::numGroups()
{
return pgroups.size();
}
void Match::addGroup(int start, int end)
{
Group g = {start, end};
pgroups.push_back(g);
}
////////////////////// Start Regex Implementations //////////////////////
Regex::Regex()
{
compiled = false;
}
Regex::~Regex()
{
if (compiled)
{
regfree(®ex);
compiled = false;
}
}
bool Regex::compile(string pattern, bool case_insensitive)
{
if (compiled)
{
regfree(®ex);
compiled = false;
}
this->pattern = pattern;
int ret;
if (case_insensitive)
ret = regcomp(®ex, pattern.c_str(), REG_ICASE | REG_EXTENDED);
else
ret = regcomp(®ex, pattern.c_str(), REG_EXTENDED);
if (ret == 0)
compiled = true;
return (ret == 0);
}
bool Regex::isCompiled()
{
return compiled;
}
std::string Regex::getPattern()
{
return pattern;
}
bool Regex::matches(std::string str)
{
if (!compiled)
return false;
int ret = regexec(®ex, str.c_str(), 0, NULL, 0);
if (ret == 0)
return true;
return false;
}
Match Regex::match(std::string str)
{
if (!compiled)
return Match("");
size_t ngroups = regex.re_nsub + 1;
regmatch_t * pgroups = (regmatch_t *) malloc(ngroups * sizeof(regmatch_t));
int ret = regexec(®ex, str.c_str(), ngroups, pgroups, 0);
if (ret == 0)
{
Match m(str);
for (int i=0; i<(int)ngroups; i++)
{
m.addGroup(pgroups[i].rm_so, pgroups[i].rm_eo);
}
free(pgroups);
return m;
}
free(pgroups);
return Match("");
}