[Regex] Replace algorithm
Hi, I'd like to replace all parts of a string with the results of calling a function, passing the match as a parameter. Some pseudo-code: --- std::string replacer(smatch& s) { return std::getenv(s[1].c_str()); } std::string const input = "This is ${USER} on ${HOST}"; boost::regex const re("\\$\\{([^\\}]+)\\}"); std::string result = boost::regex_replace(input, re, boost::bind(&replacer)); assert("This is Me on MyWorkstation" == result); --- (I'm sure there are errors above, but I hope you get the general idea). Any easy way to do something similar? // Johan
Hi, You should probably use iterators like in regex_iterator_example.cpp and prefix()/suffix() to output the text in between. Sebastian
Hi,
I'd like to replace all parts of a string with the results of calling a function, passing the match as a parameter. Some pseudo-code:
--- std::string replacer(smatch& s) { return std::getenv(s[1].c_str()); }
std::string const input = "This is ${USER} on ${HOST}"; boost::regex const re("\\$\\{([^\\}]+)\\}"); std::string result = boost::regex_replace(input, re, boost::bind(&replacer));
assert("This is Me on MyWorkstation" == result); ---
(I'm sure there are errors above, but I hope you get the general idea).
Any easy way to do something similar?
// Johan
_______________________________________________ Boost-users mailing list Boost-users@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users
Johan Nilsson wrote:
Any easy way to do something similar?
There's no wrapped-up solution, but you can use regex_iterator to iterate through the matches and replace each occurance: take a look at the code to regex_replace in boost/regex/v4/regex_replace.hpp, there's not that much to it, and you should be able to cut and paste what you need. John.
"John Maddock"
Johan Nilsson wrote:
Any easy way to do something similar?
There's no wrapped-up solution, but you can use regex_iterator to iterate through the matches and replace each occurance: take a look at the code to regex_replace in boost/regex/v4/regex_replace.hpp, there's not that much to it, and you should be able to cut and paste what you need.
Thanks for the pointer - I'll give it a try. // Johan
participants (3)
-
Johan Nilsson
-
John Maddock
-
Setzer, Sebastian (ext)