libpromeki 1.0.0-alpha
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
regex.h
Go to the documentation of this file.
1
8#pragma once
9
10
11#include <promeki/config.h>
12#if PROMEKI_ENABLE_CORE
13#include <regex>
14#include <promeki/namespace.h>
15#include <promeki/string.h>
16#include <promeki/stringlist.h>
17#include <promeki/result.h>
18
19PROMEKI_NAMESPACE_BEGIN
20
44class RegEx {
45 public:
47 using Flag = std::regex_constants::syntax_option_type;
48
50 static constexpr Flag IgnoreCase = std::regex::icase;
51
53 static constexpr Flag NoSubs = std::regex::nosubs;
54
56 static constexpr Flag Optimize = std::regex::optimize;
57
59 static constexpr Flag Collate = std::regex::collate;
60
62 static constexpr Flag ECMAScript = std::regex::ECMAScript;
63
65 static constexpr Flag Basic = std::regex::basic;
66
68 static constexpr Flag Extended = std::regex::extended;
69
71 static constexpr Flag Awk = std::regex::awk;
72
74 static constexpr Flag Grep = std::regex::grep;
75
77 static constexpr Flag EGrep = std::regex::egrep;
78
80 static constexpr Flag DefaultFlags = ECMAScript | Optimize;
81
83 RegEx() : _valid(false) {}
84
95 RegEx(const String &pattern, Flag flags = DefaultFlags) : p(pattern) {
96 try {
97 d.assign(pattern.cstr(), flags);
98 _valid = true;
99 } catch (const std::regex_error &) {
100 _valid = false;
101 }
102 }
103
114 RegEx(const char *pattern, Flag flags = DefaultFlags) : p(pattern) {
115 try {
116 d.assign(pattern, flags);
117 _valid = true;
118 } catch (const std::regex_error &) {
119 _valid = false;
120 }
121 }
122
131 static Result<RegEx> compile(const String &pattern, Flag flags = DefaultFlags) {
132 RegEx re;
133 try {
134 re.d.assign(pattern.cstr(), flags);
135 re._valid = true;
136 re.p = pattern;
137 } catch (const std::regex_error &) {
138 return makeError<RegEx>(Error::Invalid);
139 }
140 return makeResult(std::move(re));
141 }
142
152 RegEx &operator=(const String &pattern) {
153 p = pattern;
154 try {
155 d.assign(pattern.cstr());
156 _valid = true;
157 } catch (const std::regex_error &) {
158 _valid = false;
159 }
160 return *this;
161 }
162
164 bool isValid() const { return _valid; }
165
170 String pattern() const { return p; }
171
178 bool match(const String &str) const {
179 if (!_valid) return false;
180 std::smatch m;
181 return std::regex_match(str.str(), m, d);
182 }
183
190 bool search(const String &str) const {
191 if (!_valid) return false;
192 return std::regex_search(str.str(), d);
193 }
194
201 StringList matches(const String &str) const {
202 StringList matches;
203 if (!_valid) return matches;
204 std::smatch match;
205 const std::string &s = str.str();
206 auto pos = s.cbegin();
207 while (std::regex_search(pos, s.cend(), match, d)) {
208 matches += match.str();
209 pos = match.suffix().first;
210 }
211 return matches;
212 }
213
214 private:
215 std::regex d;
216 String p;
217 bool _valid = false;
218};
219
220PROMEKI_NAMESPACE_END
221
222#endif // PROMEKI_ENABLE_CORE