Skip to content

Instantly share code, notes, and snippets.

@yhirose
Created June 17, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yhirose/cb48d799db81047a4b10 to your computer and use it in GitHub Desktop.
Save yhirose/cb48d799db81047a4b10 to your computer and use it in GitHub Desktop.
regex_replace_with_lambda
template<typename T, typename F>
std::basic_string<T> regex_replace_with_lambda(
const std::basic_string<T>& str,
const std::basic_regex<T>& re,
F f)
{
typedef std::basic_string<T> StrT;
auto ret = StrT();
auto it = std::regex_token_iterator<typename StrT::const_iterator>(
std::begin(str),
std::end(str),
re);
auto last = std::regex_token_iterator<typename StrT::const_iterator>();
auto cur = std::begin(str);
while (it != last) {
auto before = StrT(cur, it->first);
if (!before.empty()) {
ret += before;
}
ret += f(it->str());
cur += before.length() + it->length();
++it;
}
if (cur != std::end(str)) {
ret += StrT(cur, std::end(str));
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment