| 1 |
#include "utils/replace_all.hpp" |
| 2 |
|
| 3 |
CPPTRACE_BEGIN_NAMESPACE |
| 4 |
namespace detail { |
| 5 |
void replace_all(std::string& str, string_view substr, string_view replacement) { |
| 6 |
std::string::size_type pos = 0; |
| 7 |
while((pos = str.find(substr.data(), pos, substr.size())) != std::string::npos) { |
| 8 |
str.replace(pos, substr.size(), replacement.data(), replacement.size()); |
| 9 |
pos += replacement.size(); |
| 10 |
} |
| 11 |
} |
| 12 |
|
| 13 |
void replace_all(std::string& str, const std::regex& re, string_view replacement) { |
| 14 |
std::smatch match; |
| 15 |
std::size_t i = 0; |
| 16 |
while(std::regex_search(str.cbegin() + i, str.cend(), match, re)) { |
| 17 |
str.replace(i + match.position(), match.length(), replacement.data(), replacement.size()); |
| 18 |
i += match.position() + replacement.size(); |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
void replace_all_dynamic(std::string& str, string_view substr, string_view replacement) { |
| 23 |
std::string::size_type pos = 0; |
| 24 |
while((pos = str.find(substr.data(), pos, substr.size())) != std::string::npos) { |
| 25 |
str.replace(pos, substr.size(), replacement.data(), replacement.size()); |
| 26 |
// advancing by one rather than replacement.length() in case replacement leads to |
| 27 |
// another replacement opportunity, e.g. folding > > > to >> > then >>> |
| 28 |
pos++; |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
void replace_all_template(std::string& str, const std::pair<std::regex, string_view>& rule) { |
| 33 |
const auto& re = rule.first; |
| 34 |
const auto& replacement = rule.second; |
| 35 |
std::smatch match; |
| 36 |
std::size_t cursor = 0; |
| 37 |
while(std::regex_search(str.cbegin() + cursor, str.cend(), match, re)) { |
| 38 |
// find matching > |
| 39 |
const std::size_t match_begin = cursor + match.position(); |
| 40 |
std::size_t end = match_begin + match.length(); |
| 41 |
for(int c = 1; end < str.size() && c > 0; end++) { |
| 42 |
if(str[end] == '<') { |
| 43 |
c++; |
| 44 |
} else if(str[end] == '>') { |
| 45 |
c--; |
| 46 |
} |
| 47 |
} |
| 48 |
// make the replacement |
| 49 |
str.replace(match_begin, end - match_begin, replacement.data(), replacement.size()); |
| 50 |
cursor = match_begin + replacement.size(); |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
CPPTRACE_END_NAMESPACE |