[英]Regex search & replace group in C++?
The best I can come up with is: 我能想到的最好的是:
#include <boost/algorithm/string/replace.hpp>
#include <boost/regex.hpp>
#include <iostream>
using namespace std;
int main() {
string dog = "scooby-doo";
boost::regex pattern("(\\w+)-doo");
boost::smatch groups;
if (boost::regex_match(dog, groups, pattern))
boost::replace_all(dog, string(groups[1]), "scrappy");
cout << dog << endl;
}
with output: 输出:
scrappy-doo
.. is there a simpler way of doing this, that doesn't involve doing two distinct searches? ..是否有一种更简单的方法,而不涉及进行两个不同的搜索? Maybe with the new C++11 stuff (although I'm not sure that it's compatible with gcc atm?)
也许使用了新的C ++ 11东西(尽管我不确定它是否与gcc atm兼容?)
std::regex_replace
should do the trick. std::regex_replace
应该可以解决问题。 The provided example is pretty close to your problem, even to the point of showing how to shove the answer straight into cout
if you want. 所提供的示例非常接近您的问题,甚至可以显示出如何根据需要将答案直接推到
cout
。 Pasted here for posterity: 为了后代粘贴在这里:
#include <iostream>
#include <iterator>
#include <regex>
#include <string>
int main()
{
std::string text = "Quick brown fox";
std::regex vowel_re("a|e|i|o|u");
// write the results to an output iterator
std::regex_replace(std::ostreambuf_iterator<char>(std::cout),
text.begin(), text.end(), vowel_re, "*");
// construct a string holding the results
std::cout << '\n' << std::regex_replace(text, vowel_re, "[$&]") << '\n';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.