fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <string>
  4. #include <regex>
  5. using namespace std;
  6.  
  7. int gate_id = 0;
  8.  
  9. template<class BidirIt, class Traits, class CharT, class UnaryFunction>
  10. std::basic_string<CharT> regex_replace(BidirIt first, BidirIt last,
  11. const std::basic_regex<CharT,Traits>& re, UnaryFunction f)
  12. {
  13. std::basic_string<CharT> s;
  14.  
  15. typename std::match_results<BidirIt>::difference_type
  16. positionOfLastMatch = 0;
  17. auto endOfLastMatch = first;
  18.  
  19. auto callback = [&](const std::match_results<BidirIt>& match)
  20. {
  21. auto positionOfThisMatch = match.position(0);
  22. auto diff = positionOfThisMatch - positionOfLastMatch;
  23.  
  24. auto startOfThisMatch = endOfLastMatch;
  25. std::advance(startOfThisMatch, diff);
  26.  
  27. s.append(endOfLastMatch, startOfThisMatch);
  28. s.append(f(match));
  29.  
  30. auto lengthOfMatch = match.length(0);
  31.  
  32. positionOfLastMatch = positionOfThisMatch + lengthOfMatch;
  33.  
  34. endOfLastMatch = startOfThisMatch;
  35. std::advance(endOfLastMatch, lengthOfMatch);
  36. };
  37.  
  38. std::sregex_iterator begin(first, last, re), end;
  39. std::for_each(begin, end, callback);
  40.  
  41. s.append(endOfLastMatch, last);
  42.  
  43. return s;
  44. }
  45.  
  46. template<class Traits, class CharT, class UnaryFunction>
  47. std::string regex_replace(const std::string& s,
  48. const std::basic_regex<CharT,Traits>& re, UnaryFunction f)
  49. {
  50. return regex_replace(s.cbegin(), s.cend(), re, f);
  51. }
  52.  
  53. std::string my_callback(const std::smatch& m) {
  54. gate_id++;
  55. stringstream s;
  56. s << "g" << gate_id << "()";
  57. return s.str();
  58. }
  59.  
  60. int main() {
  61. gate_id = 0;
  62. std::string s = "g500() g600() g200()\n g1()";
  63. std::cout << regex_replace(s, regex("g\\S*\\(\\)"), my_callback) << std::endl;
  64. return 0;
  65. }
Success #stdin #stdout 0s 4504KB
stdin
Standard input is empty
stdout
g1() g2() g3()
 g4()