-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathRegExp.cpp
69 lines (59 loc) · 1.62 KB
/
RegExp.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
#include <stdexcept>
#include <regex.h>
#include "RegExp.h"
RegExp::RegExp(const std::string ®ex)
: RegExp(regex.c_str()) {}
RegExp::RegExp(const char *regex) {
R(regcomp(&re_, regex, REG_EXTENDED), regex);
owned_ = true;
}
RegExp::~RegExp() {
release();
}
void RegExp::release() {
if (owned_)
regfree(&re_);
owned_ = false;
}
bool RegExp::exec(const std::string &match, std::vector<Match> &result,
size_t offset) {
return exec(match.c_str() + offset, result, offset == 0);
}
bool RegExp::exec(const char *against, RegExp::Matches &result, bool bol) {
constexpr auto MaxMatches = 20u;
regmatch_t matches[MaxMatches];
auto res = regexec(&re_, against, MaxMatches, matches,
bol ? 0 : REG_NOTBOL);
if (res == REG_NOMATCH) return false;
R(res);
result.clear();
for (auto i = 0u; i < MaxMatches; ++i) {
if (matches[i].rm_so == -1) break;
result.emplace_back(matches[i].rm_so, matches[i].rm_eo);
}
return true;
}
void RegExp::R(int e) const {
if (!e) return;
char error[1024];
regerror(e, &re_, error, sizeof(error));
throw std::runtime_error(error);
}
void RegExp::R(int e, const char *context) const {
if (!e) return;
char error[1024];
regerror(e, &re_, error, sizeof(error));
throw std::runtime_error(error + std::string(" in '") + context + "'");
}
RegExp::RegExp(RegExp &&exp)
: re_(exp.re_) {
exp.owned_ = false;
owned_ = true;
}
RegExp &RegExp::operator=(RegExp &&exp) {
release();
re_ = exp.re_;
exp.owned_ = false;
owned_ = true;
return *this;
}