我想要這種功能,並不喜歡答案「使用提升」。本傑明的答案的問題是它提供了所有的令牌。這意味着您不知道哪個令牌是匹配的,並且不允許您使用捕獲組。這樣做:
// clang++ -std=c++11 -stdlib=libc++ -o test test.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include <regex>
namespace std
{
template<class BidirIt, class Traits, class CharT, class UnaryFunction>
std::basic_string<CharT> regex_replace(BidirIt first, BidirIt last,
const std::basic_regex<CharT,Traits>& re, UnaryFunction f)
{
std::basic_string<CharT> s;
typename std::match_results<BidirIt>::difference_type
positionOfLastMatch = 0;
auto endOfLastMatch = first;
auto callback = [&](const std::match_results<BidirIt>& match)
{
auto positionOfThisMatch = match.position(0);
auto diff = positionOfThisMatch - positionOfLastMatch;
auto startOfThisMatch = endOfLastMatch;
std::advance(startOfThisMatch, diff);
s.append(endOfLastMatch, startOfThisMatch);
s.append(f(match));
auto lengthOfMatch = match.length(0);
positionOfLastMatch = positionOfThisMatch + lengthOfMatch;
endOfLastMatch = startOfThisMatch;
std::advance(endOfLastMatch, lengthOfMatch);
};
std::regex_iterator<BidirIt> begin(first, last, re), end;
std::for_each(begin, end, callback);
s.append(endOfLastMatch, last);
return s;
}
template<class Traits, class CharT, class UnaryFunction>
std::string regex_replace(const std::string& s,
const std::basic_regex<CharT,Traits>& re, UnaryFunction f)
{
return regex_replace(s.cbegin(), s.cend(), re, f);
}
} // namespace std
using namespace std;
std::string my_callback(const std::smatch& m) {
int int_m = atoi(m.str(0).c_str());
return std::to_string(int_m + 1);
}
int main(int argc, char *argv[])
{
cout << regex_replace("my values are 9, 19", regex("\\d+"),
my_callback) << endl;
cout << regex_replace("my values are 9, 19", regex("\\d+"),
[](const std::smatch& m){
int int_m = atoi(m.str(0).c_str());
return std::to_string(int_m + 1);
}
) << endl;
return 0;
}
它的工作原理。但我認爲Boost是一個更好的解決方案。 http://stackoverflow.com/questions/11508798/conditionally-replace-regex-matches-in-string – duleshi