forked from jeremy-rifkin/cpptrace
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreplace_all.cpp
More file actions
54 lines (50 loc) · 2.24 KB
/
replace_all.cpp
File metadata and controls
54 lines (50 loc) · 2.24 KB
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
#include "utils/replace_all.hpp"
CPPTRACE_BEGIN_NAMESPACE
namespace detail {
void replace_all(std::string& str, string_view substr, string_view replacement) {
std::string::size_type pos = 0;
while((pos = str.find(substr.data(), pos, substr.size())) != std::string::npos) {
str.replace(pos, substr.size(), replacement.data(), replacement.size());
pos += replacement.size();
}
}
void replace_all(std::string& str, const std::regex& re, string_view replacement) {
std::smatch match;
std::size_t i = 0;
while(std::regex_search(str.cbegin() + i, str.cend(), match, re)) {
str.replace(i + match.position(), match.length(), replacement.data(), replacement.size());
i += match.position() + replacement.size();
}
}
void replace_all_dynamic(std::string& str, string_view substr, string_view replacement) {
std::string::size_type pos = 0;
while((pos = str.find(substr.data(), pos, substr.size())) != std::string::npos) {
str.replace(pos, substr.size(), replacement.data(), replacement.size());
// advancing by one rather than replacement.length() in case replacement leads to
// another replacement opportunity, e.g. folding > > > to >> > then >>>
pos++;
}
}
void replace_all_template(std::string& str, const std::pair<std::regex, string_view>& rule) {
const auto& re = rule.first;
const auto& replacement = rule.second;
std::smatch match;
std::size_t cursor = 0;
while(std::regex_search(str.cbegin() + cursor, str.cend(), match, re)) {
// find matching >
const std::size_t match_begin = cursor + match.position();
std::size_t end = match_begin + match.length();
for(int c = 1; end < str.size() && c > 0; end++) {
if(str[end] == '<') {
c++;
} else if(str[end] == '>') {
c--;
}
}
// make the replacement
str.replace(match_begin, end - match_begin, replacement.data(), replacement.size());
cursor = match_begin + replacement.size();
}
}
}
CPPTRACE_END_NAMESPACE