C++ Regex search&;替换C+中的组+;?
我能想到的最好办法是:C++ Regex search&;替换C+中的组+;?,c++,regex,C++,Regex,我能想到的最好办法是: #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 gr
#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;
}
。。有没有一种更简单的方法,不需要进行两次不同的搜索?也许使用新的C++11工具(尽管我不确定它是否与gcc atm兼容?应该可以做到这一点。所提供的示例非常接近您的问题,甚至可以说明如果您愿意,如何将答案直接插入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';
}
#包括
#包括
#包括
#包括
int main()
{
std::string text=“Quick brown fox”;
标准:正则元音“u re”(“a | e | i | o | u”);
//将结果写入输出迭代器
std::regex_replace(std::ostreambuf_迭代器(std::cout),
text.begin(),text.end(),元音为“*”;
//构造一个包含结果的字符串
std::我明白了。我发现这个界面违反直觉,因为您必须使用$x语法有效地重建一个新字符串,以表示前一个字符串中的正则表达式组。也就是说,我想不出更好的了
#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';
}