我能想到的最好的是:
#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;
}
输出:
scrappy-doo
.. 有没有一种更简单的方法,不需要进行两次不同的搜索?也许使用新的 C++11 东西(虽然我不确定它是否与 gcc atm 兼容?)
最佳答案
std::regex_replace
应该做的伎俩。提供的示例非常接近您的问题,甚至可以展示如何将答案直接插入 cout
如果您愿意。粘贴在这里供后代使用:
#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';
}
关于c++ - C++ 中的正则表达式搜索和替换组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17033341/