regex replace with callback in c++11?its possible c++ regex evaluator with lambdas like ruby?C++ format specifier for regex_replaceConditionally replace regex matches in stringHow to match only those numbers which have an even number of `%`s preceding them?Parse (replace) in C++ std::stringSelectively replace (") doublequotes in a std::string in C++How to Simplify C++ Boolean ComparisonsRegex to replace all occurrences between two matchesHow do I use std::regex_replace to replace string into lowercase?Find $number and then replace it with $number+1?A comprehensive regex for phone number validationWhat is a callback function?How to replace all occurrences of a string in JavaScriptHow can I pass a parameter to a setTimeout() callback?RegEx match open tags except XHTML self-contained tagsWhat does T&& (double ampersand) mean in C++11?C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?What is a lambda expression in C++11?What is the difference between 'typedef' and 'using' in C++11?How to access the correct `this` inside a callback?

Why don't countries like Japan just print more money?

Identifying a distribution

`-` in tar xzf -

How to make clear to people I don't want to answer their "Where are you from?" question?

How did Gollum enter Moria?

Encounter design and XP thresholds

Do I need a shock-proof watch for cycling?

Can humans ever directly see a few photons at a time? Can a human see a single photon?

Will generated tokens be progressively stronger when using Cathar's Crusade and Sorin, Grim Nemesis?

Is "Busen" just the area between the breasts?

LWC - Local Dev - How can I run the local server on HTTPS?

Causes of High CHTs

UK - Working without a contract. I resign and guy wants to sue me

Is declining an undergraduate award which causes me discomfort appropriate?

Confusion over 220 and 230 volt outlets

What is appropriate short form for "laboratoires" in French?

Can I enter the UK for 24 hours from a Schengen area, holding an Indian passport?

What is the origin of Scooby-Doo's name?

Shooting someone's past self using special relativity

What can I do with a research project that is my university’s intellectual property?

Why does Linux list NVMe drives as /dev/nvme0 instead of /dev/sda?

Why are < or > requried to use /dev/tcp

How long would it take to cross the Channel in 1890's?

Are all Ringwraiths called Nazgûl in LotR?



regex replace with callback in c++11?


its possible c++ regex evaluator with lambdas like ruby?C++ format specifier for regex_replaceConditionally replace regex matches in stringHow to match only those numbers which have an even number of `%`s preceding them?Parse (replace) in C++ std::stringSelectively replace (") doublequotes in a std::string in C++How to Simplify C++ Boolean ComparisonsRegex to replace all occurrences between two matchesHow do I use std::regex_replace to replace string into lowercase?Find $number and then replace it with $number+1?A comprehensive regex for phone number validationWhat is a callback function?How to replace all occurrences of a string in JavaScriptHow can I pass a parameter to a setTimeout() callback?RegEx match open tags except XHTML self-contained tagsWhat does T&& (double ampersand) mean in C++11?C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?What is a lambda expression in C++11?What is the difference between 'typedef' and 'using' in C++11?How to access the correct `this` inside a callback?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








17















Is there a function of regex replacement that will send the matches to user function and then substitute the return value:



I've tried this method, but it obviously doesn't work:



cout << regex_replace("my values are 9, 19", regex("d+"), my_callback);


and function:



std::string my_callback(std::string &m) 
int int_m = atoi(m.c_str());
return std::to_string(int_m + 1);



and the result should be: my values are 10, 20



I mean similar mode of working like php's preg_replace_callback or python's re.sub(pattern, callback, subject)



And I mean the latest 4.9 gcc, that is capable of regex without boost.










share|improve this question






























    17















    Is there a function of regex replacement that will send the matches to user function and then substitute the return value:



    I've tried this method, but it obviously doesn't work:



    cout << regex_replace("my values are 9, 19", regex("d+"), my_callback);


    and function:



    std::string my_callback(std::string &m) 
    int int_m = atoi(m.c_str());
    return std::to_string(int_m + 1);



    and the result should be: my values are 10, 20



    I mean similar mode of working like php's preg_replace_callback or python's re.sub(pattern, callback, subject)



    And I mean the latest 4.9 gcc, that is capable of regex without boost.










    share|improve this question


























      17












      17








      17


      5






      Is there a function of regex replacement that will send the matches to user function and then substitute the return value:



      I've tried this method, but it obviously doesn't work:



      cout << regex_replace("my values are 9, 19", regex("d+"), my_callback);


      and function:



      std::string my_callback(std::string &m) 
      int int_m = atoi(m.c_str());
      return std::to_string(int_m + 1);



      and the result should be: my values are 10, 20



      I mean similar mode of working like php's preg_replace_callback or python's re.sub(pattern, callback, subject)



      And I mean the latest 4.9 gcc, that is capable of regex without boost.










      share|improve this question
















      Is there a function of regex replacement that will send the matches to user function and then substitute the return value:



      I've tried this method, but it obviously doesn't work:



      cout << regex_replace("my values are 9, 19", regex("d+"), my_callback);


      and function:



      std::string my_callback(std::string &m) 
      int int_m = atoi(m.c_str());
      return std::to_string(int_m + 1);



      and the result should be: my values are 10, 20



      I mean similar mode of working like php's preg_replace_callback or python's re.sub(pattern, callback, subject)



      And I mean the latest 4.9 gcc, that is capable of regex without boost.







      c++ regex c++11 callback






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 24 '14 at 18:26







      rsk82

















      asked Mar 24 '14 at 18:04









      rsk82rsk82

      10.1k35108202




      10.1k35108202






















          3 Answers
          3






          active

          oldest

          votes


















          18














          I wanted this kind of function and didn't like the answer "use boost". The problem with Benjamin's answer is it provides all the tokens. This means you don't know which token is a match and it doesn't let you use capture groups. This does:



          // 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;






          share|improve this answer

























          • +1 for the solution, but you need to use a namespace other than std. Currently your example has undefined behavior, since you're overloading std::regex_replace, not specializing it.

            – andreee
            May 6 at 8:17


















          11














          You could use a regex_token_iterator



          #include <iostream>
          #include <algorithm>
          #include <regex>
          #include <string>
          #include <sstream>

          int main()

          std::string input_text = "my values are 9, 19";
          std::string output_text;
          auto callback = [&](std::string const& m)
          std::istringstream iss(m);
          int n;
          if(iss >> n)

          output_text += std::to_string(n+1);

          else

          output_text += m;

          ;

          std::regex re("\d+");
          std::sregex_token_iterator
          begin(input_text.begin(), input_text.end(), re, -1,0),
          end;
          std::for_each(begin,end,callback);

          std::cout << output_text;



          Note that the -1,0 in the argument list of the iterator constructor is a list specifying the submatches we want to iterate over. The -1 is for non-matching sections, and the 0 is for the first submatch.



          Also note that I have not used the c++11 regex functionality extensively and am no expert in it. So there may be problems with this code. But for your specific input, I tested it and it seems to produce the expected results. If you find any input set for which it doesn't work, please let me know.






          share|improve this answer




















          • 1





            It works. But I think Boost is a better solution. stackoverflow.com/questions/11508798/…

            – duleshi
            Sep 18 '15 at 9:15


















          0














          That kind of functionality only exists in the Boost library version of regex_replace, which can have the custom formatter. Unfortunately, the standard C++11 implementation requires the replacement format argument must be a string.



          Here is the documentation on regex_replace: http://www.cplusplus.com/reference/regex/match_replace/






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f22617209%2fregex-replace-with-callback-in-c11%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            18














            I wanted this kind of function and didn't like the answer "use boost". The problem with Benjamin's answer is it provides all the tokens. This means you don't know which token is a match and it doesn't let you use capture groups. This does:



            // 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;






            share|improve this answer

























            • +1 for the solution, but you need to use a namespace other than std. Currently your example has undefined behavior, since you're overloading std::regex_replace, not specializing it.

              – andreee
              May 6 at 8:17















            18














            I wanted this kind of function and didn't like the answer "use boost". The problem with Benjamin's answer is it provides all the tokens. This means you don't know which token is a match and it doesn't let you use capture groups. This does:



            // 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;






            share|improve this answer

























            • +1 for the solution, but you need to use a namespace other than std. Currently your example has undefined behavior, since you're overloading std::regex_replace, not specializing it.

              – andreee
              May 6 at 8:17













            18












            18








            18







            I wanted this kind of function and didn't like the answer "use boost". The problem with Benjamin's answer is it provides all the tokens. This means you don't know which token is a match and it doesn't let you use capture groups. This does:



            // 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;






            share|improve this answer















            I wanted this kind of function and didn't like the answer "use boost". The problem with Benjamin's answer is it provides all the tokens. This means you don't know which token is a match and it doesn't let you use capture groups. This does:



            // 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;







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 6 '18 at 5:56









            Violet Giraffe

            15.2k29140260




            15.2k29140260










            answered May 30 '16 at 0:47









            John MartinJohn Martin

            19612




            19612












            • +1 for the solution, but you need to use a namespace other than std. Currently your example has undefined behavior, since you're overloading std::regex_replace, not specializing it.

              – andreee
              May 6 at 8:17

















            • +1 for the solution, but you need to use a namespace other than std. Currently your example has undefined behavior, since you're overloading std::regex_replace, not specializing it.

              – andreee
              May 6 at 8:17
















            +1 for the solution, but you need to use a namespace other than std. Currently your example has undefined behavior, since you're overloading std::regex_replace, not specializing it.

            – andreee
            May 6 at 8:17





            +1 for the solution, but you need to use a namespace other than std. Currently your example has undefined behavior, since you're overloading std::regex_replace, not specializing it.

            – andreee
            May 6 at 8:17













            11














            You could use a regex_token_iterator



            #include <iostream>
            #include <algorithm>
            #include <regex>
            #include <string>
            #include <sstream>

            int main()

            std::string input_text = "my values are 9, 19";
            std::string output_text;
            auto callback = [&](std::string const& m)
            std::istringstream iss(m);
            int n;
            if(iss >> n)

            output_text += std::to_string(n+1);

            else

            output_text += m;

            ;

            std::regex re("\d+");
            std::sregex_token_iterator
            begin(input_text.begin(), input_text.end(), re, -1,0),
            end;
            std::for_each(begin,end,callback);

            std::cout << output_text;



            Note that the -1,0 in the argument list of the iterator constructor is a list specifying the submatches we want to iterate over. The -1 is for non-matching sections, and the 0 is for the first submatch.



            Also note that I have not used the c++11 regex functionality extensively and am no expert in it. So there may be problems with this code. But for your specific input, I tested it and it seems to produce the expected results. If you find any input set for which it doesn't work, please let me know.






            share|improve this answer




















            • 1





              It works. But I think Boost is a better solution. stackoverflow.com/questions/11508798/…

              – duleshi
              Sep 18 '15 at 9:15















            11














            You could use a regex_token_iterator



            #include <iostream>
            #include <algorithm>
            #include <regex>
            #include <string>
            #include <sstream>

            int main()

            std::string input_text = "my values are 9, 19";
            std::string output_text;
            auto callback = [&](std::string const& m)
            std::istringstream iss(m);
            int n;
            if(iss >> n)

            output_text += std::to_string(n+1);

            else

            output_text += m;

            ;

            std::regex re("\d+");
            std::sregex_token_iterator
            begin(input_text.begin(), input_text.end(), re, -1,0),
            end;
            std::for_each(begin,end,callback);

            std::cout << output_text;



            Note that the -1,0 in the argument list of the iterator constructor is a list specifying the submatches we want to iterate over. The -1 is for non-matching sections, and the 0 is for the first submatch.



            Also note that I have not used the c++11 regex functionality extensively and am no expert in it. So there may be problems with this code. But for your specific input, I tested it and it seems to produce the expected results. If you find any input set for which it doesn't work, please let me know.






            share|improve this answer




















            • 1





              It works. But I think Boost is a better solution. stackoverflow.com/questions/11508798/…

              – duleshi
              Sep 18 '15 at 9:15













            11












            11








            11







            You could use a regex_token_iterator



            #include <iostream>
            #include <algorithm>
            #include <regex>
            #include <string>
            #include <sstream>

            int main()

            std::string input_text = "my values are 9, 19";
            std::string output_text;
            auto callback = [&](std::string const& m)
            std::istringstream iss(m);
            int n;
            if(iss >> n)

            output_text += std::to_string(n+1);

            else

            output_text += m;

            ;

            std::regex re("\d+");
            std::sregex_token_iterator
            begin(input_text.begin(), input_text.end(), re, -1,0),
            end;
            std::for_each(begin,end,callback);

            std::cout << output_text;



            Note that the -1,0 in the argument list of the iterator constructor is a list specifying the submatches we want to iterate over. The -1 is for non-matching sections, and the 0 is for the first submatch.



            Also note that I have not used the c++11 regex functionality extensively and am no expert in it. So there may be problems with this code. But for your specific input, I tested it and it seems to produce the expected results. If you find any input set for which it doesn't work, please let me know.






            share|improve this answer















            You could use a regex_token_iterator



            #include <iostream>
            #include <algorithm>
            #include <regex>
            #include <string>
            #include <sstream>

            int main()

            std::string input_text = "my values are 9, 19";
            std::string output_text;
            auto callback = [&](std::string const& m)
            std::istringstream iss(m);
            int n;
            if(iss >> n)

            output_text += std::to_string(n+1);

            else

            output_text += m;

            ;

            std::regex re("\d+");
            std::sregex_token_iterator
            begin(input_text.begin(), input_text.end(), re, -1,0),
            end;
            std::for_each(begin,end,callback);

            std::cout << output_text;



            Note that the -1,0 in the argument list of the iterator constructor is a list specifying the submatches we want to iterate over. The -1 is for non-matching sections, and the 0 is for the first submatch.



            Also note that I have not used the c++11 regex functionality extensively and am no expert in it. So there may be problems with this code. But for your specific input, I tested it and it seems to produce the expected results. If you find any input set for which it doesn't work, please let me know.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 24 '14 at 18:51

























            answered Mar 24 '14 at 18:42









            Benjamin LindleyBenjamin Lindley

            87.2k4142234




            87.2k4142234







            • 1





              It works. But I think Boost is a better solution. stackoverflow.com/questions/11508798/…

              – duleshi
              Sep 18 '15 at 9:15












            • 1





              It works. But I think Boost is a better solution. stackoverflow.com/questions/11508798/…

              – duleshi
              Sep 18 '15 at 9:15







            1




            1





            It works. But I think Boost is a better solution. stackoverflow.com/questions/11508798/…

            – duleshi
            Sep 18 '15 at 9:15





            It works. But I think Boost is a better solution. stackoverflow.com/questions/11508798/…

            – duleshi
            Sep 18 '15 at 9:15











            0














            That kind of functionality only exists in the Boost library version of regex_replace, which can have the custom formatter. Unfortunately, the standard C++11 implementation requires the replacement format argument must be a string.



            Here is the documentation on regex_replace: http://www.cplusplus.com/reference/regex/match_replace/






            share|improve this answer



























              0














              That kind of functionality only exists in the Boost library version of regex_replace, which can have the custom formatter. Unfortunately, the standard C++11 implementation requires the replacement format argument must be a string.



              Here is the documentation on regex_replace: http://www.cplusplus.com/reference/regex/match_replace/






              share|improve this answer

























                0












                0








                0







                That kind of functionality only exists in the Boost library version of regex_replace, which can have the custom formatter. Unfortunately, the standard C++11 implementation requires the replacement format argument must be a string.



                Here is the documentation on regex_replace: http://www.cplusplus.com/reference/regex/match_replace/






                share|improve this answer













                That kind of functionality only exists in the Boost library version of regex_replace, which can have the custom formatter. Unfortunately, the standard C++11 implementation requires the replacement format argument must be a string.



                Here is the documentation on regex_replace: http://www.cplusplus.com/reference/regex/match_replace/







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 24 '14 at 18:32









                blockchaindevblockchaindev

                2,04011627




                2,04011627



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f22617209%2fregex-replace-with-callback-in-c11%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript