You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

str_replace.h 9.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. //
  2. // Copyright 2017 The Abseil Authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. // -----------------------------------------------------------------------------
  17. // File: str_replace.h
  18. // -----------------------------------------------------------------------------
  19. //
  20. // This file defines `absl::StrReplaceAll()`, a general-purpose string
  21. // replacement function designed for large, arbitrary text substitutions,
  22. // especially on strings which you are receiving from some other system for
  23. // further processing (e.g. processing regular expressions, escaping HTML
  24. // entities, etc.). `StrReplaceAll` is designed to be efficient even when only
  25. // one substitution is being performed, or when substitution is rare.
  26. //
  27. // If the string being modified is known at compile-time, and the substitutions
  28. // vary, `absl::Substitute()` may be a better choice.
  29. //
  30. // Example:
  31. //
  32. // std::string html_escaped = absl::StrReplaceAll(user_input, {
  33. // {"&", "&"},
  34. // {"<", "&lt;"},
  35. // {">", "&gt;"},
  36. // {"\"", "&quot;"},
  37. // {"'", "&#39;"}});
  38. #ifndef ABSL_STRINGS_STR_REPLACE_H_
  39. #define ABSL_STRINGS_STR_REPLACE_H_
  40. #include <string>
  41. #include <utility>
  42. #include <vector>
  43. #include "absl/base/attributes.h"
  44. #include "absl/strings/string_view.h"
  45. namespace absl
  46. {
  47. ABSL_NAMESPACE_BEGIN
  48. // StrReplaceAll()
  49. //
  50. // Replaces character sequences within a given string with replacements provided
  51. // within an initializer list of key/value pairs. Candidate replacements are
  52. // considered in order as they occur within the string, with earlier matches
  53. // taking precedence, and longer matches taking precedence for candidates
  54. // starting at the same position in the string. Once a substitution is made, the
  55. // replaced text is not considered for any further substitutions.
  56. //
  57. // Example:
  58. //
  59. // std::string s = absl::StrReplaceAll(
  60. // "$who bought $count #Noun. Thanks $who!",
  61. // {{"$count", absl::StrCat(5)},
  62. // {"$who", "Bob"},
  63. // {"#Noun", "Apples"}});
  64. // EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s);
  65. ABSL_MUST_USE_RESULT std::string StrReplaceAll(
  66. absl::string_view s,
  67. std::initializer_list<std::pair<absl::string_view, absl::string_view>>
  68. replacements
  69. );
  70. // Overload of `StrReplaceAll()` to accept a container of key/value replacement
  71. // pairs (typically either an associative map or a `std::vector` of `std::pair`
  72. // elements). A vector of pairs is generally more efficient.
  73. //
  74. // Examples:
  75. //
  76. // std::map<const absl::string_view, const absl::string_view> replacements;
  77. // replacements["$who"] = "Bob";
  78. // replacements["$count"] = "5";
  79. // replacements["#Noun"] = "Apples";
  80. // std::string s = absl::StrReplaceAll(
  81. // "$who bought $count #Noun. Thanks $who!",
  82. // replacements);
  83. // EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s);
  84. //
  85. // // A std::vector of std::pair elements can be more efficient.
  86. // std::vector<std::pair<const absl::string_view, std::string>> replacements;
  87. // replacements.push_back({"&", "&amp;"});
  88. // replacements.push_back({"<", "&lt;"});
  89. // replacements.push_back({">", "&gt;"});
  90. // std::string s = absl::StrReplaceAll("if (ptr < &foo)",
  91. // replacements);
  92. // EXPECT_EQ("if (ptr &lt; &amp;foo)", s);
  93. template<typename StrToStrMapping>
  94. std::string StrReplaceAll(absl::string_view s, const StrToStrMapping& replacements);
  95. // Overload of `StrReplaceAll()` to replace character sequences within a given
  96. // output string *in place* with replacements provided within an initializer
  97. // list of key/value pairs, returning the number of substitutions that occurred.
  98. //
  99. // Example:
  100. //
  101. // std::string s = std::string("$who bought $count #Noun. Thanks $who!");
  102. // int count;
  103. // count = absl::StrReplaceAll({{"$count", absl::StrCat(5)},
  104. // {"$who", "Bob"},
  105. // {"#Noun", "Apples"}}, &s);
  106. // EXPECT_EQ(count, 4);
  107. // EXPECT_EQ("Bob bought 5 Apples. Thanks Bob!", s);
  108. int StrReplaceAll(
  109. std::initializer_list<std::pair<absl::string_view, absl::string_view>>
  110. replacements,
  111. std::string* target
  112. );
  113. // Overload of `StrReplaceAll()` to replace patterns within a given output
  114. // string *in place* with replacements provided within a container of key/value
  115. // pairs.
  116. //
  117. // Example:
  118. //
  119. // std::string s = std::string("if (ptr < &foo)");
  120. // int count = absl::StrReplaceAll({{"&", "&amp;"},
  121. // {"<", "&lt;"},
  122. // {">", "&gt;"}}, &s);
  123. // EXPECT_EQ(count, 2);
  124. // EXPECT_EQ("if (ptr &lt; &amp;foo)", s);
  125. template<typename StrToStrMapping>
  126. int StrReplaceAll(const StrToStrMapping& replacements, std::string* target);
  127. // Implementation details only, past this point.
  128. namespace strings_internal
  129. {
  130. struct ViableSubstitution
  131. {
  132. absl::string_view old;
  133. absl::string_view replacement;
  134. size_t offset;
  135. ViableSubstitution(absl::string_view old_str, absl::string_view replacement_str, size_t offset_val) :
  136. old(old_str),
  137. replacement(replacement_str),
  138. offset(offset_val)
  139. {
  140. }
  141. // One substitution occurs "before" another (takes priority) if either
  142. // it has the lowest offset, or it has the same offset but a larger size.
  143. bool OccursBefore(const ViableSubstitution& y) const
  144. {
  145. if (offset != y.offset)
  146. return offset < y.offset;
  147. return old.size() > y.old.size();
  148. }
  149. };
  150. // Build a vector of ViableSubstitutions based on the given list of
  151. // replacements. subs can be implemented as a priority_queue. However, it turns
  152. // out that most callers have small enough a list of substitutions that the
  153. // overhead of such a queue isn't worth it.
  154. template<typename StrToStrMapping>
  155. std::vector<ViableSubstitution> FindSubstitutions(
  156. absl::string_view s, const StrToStrMapping& replacements
  157. )
  158. {
  159. std::vector<ViableSubstitution> subs;
  160. subs.reserve(replacements.size());
  161. for (const auto& rep : replacements)
  162. {
  163. using std::get;
  164. absl::string_view old(get<0>(rep));
  165. size_t pos = s.find(old);
  166. if (pos == s.npos)
  167. continue;
  168. // Ignore attempts to replace "". This condition is almost never true,
  169. // but above condition is frequently true. That's why we test for this
  170. // now and not before.
  171. if (old.empty())
  172. continue;
  173. subs.emplace_back(old, get<1>(rep), pos);
  174. // Insertion sort to ensure the last ViableSubstitution comes before
  175. // all the others.
  176. size_t index = subs.size();
  177. while (--index && subs[index - 1].OccursBefore(subs[index]))
  178. {
  179. std::swap(subs[index], subs[index - 1]);
  180. }
  181. }
  182. return subs;
  183. }
  184. int ApplySubstitutions(absl::string_view s, std::vector<ViableSubstitution>* subs_ptr, std::string* result_ptr);
  185. } // namespace strings_internal
  186. template<typename StrToStrMapping>
  187. std::string StrReplaceAll(absl::string_view s, const StrToStrMapping& replacements)
  188. {
  189. auto subs = strings_internal::FindSubstitutions(s, replacements);
  190. std::string result;
  191. result.reserve(s.size());
  192. strings_internal::ApplySubstitutions(s, &subs, &result);
  193. return result;
  194. }
  195. template<typename StrToStrMapping>
  196. int StrReplaceAll(const StrToStrMapping& replacements, std::string* target)
  197. {
  198. auto subs = strings_internal::FindSubstitutions(*target, replacements);
  199. if (subs.empty())
  200. return 0;
  201. std::string result;
  202. result.reserve(target->size());
  203. int substitutions =
  204. strings_internal::ApplySubstitutions(*target, &subs, &result);
  205. target->swap(result);
  206. return substitutions;
  207. }
  208. ABSL_NAMESPACE_END
  209. } // namespace absl
  210. #endif // ABSL_STRINGS_STR_REPLACE_H_