c++ - C++ 中的正则表达式搜索和替换组?

标签 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 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/

相关文章:

javascript - 正则表达式 - 使用仅匹配数字的量词匹配字符范围

regex - R字符串在拆分时删除标点符号

c++ - 这个运算符在 C++ 中有什么作用?

c++ - C++11 中的 3 默认成员弃用规则

mysql - 仅获取包含少于 4 位数字的行

javascript - 在 Regex 问题 : TypeError: cannot read property "1" from null 中需要帮助

c++ - 为什么类中的initializer_list没有声明为 "const std::initializer_list & li"?

c++ - Eigen 叉积类型转换

c++ - Mac 上 C++ 的 Jupyter 内核

javascript - 正则表达式用于删除js中的css规则