c++ - 如何使用 regex_replace?

标签 c++ regex

asking this question on SO 之后,我意识到我需要用另一个字符串替换一个字符串中的所有匹配项。在我的例子中,我想用 `\s*' 替换所有出现的空格(即任何数量的空格都将匹配)。

所以我设计了以下内容:

#include <string>
#include <regex>

int main ()
{
  const std::string someString = "here is some text";
  const std::string output = std::regex_replace(someString.c_str(), std::regex("\\s+"), "\\s*");
}

此操作失败,输出如下:

error: no matching function for call to ‘regex_replace(const char*, std::regex, const char [4])

工作示例:http://ideone.com/yEpgXy

不要气馁,我前往 cplusplus.com 并发现我的尝试实际上与 regex_replace 函数的第一个原型(prototype)非常匹配,所以令我惊讶的是编译器无法运行它(供您引用:http://www.cplusplus.com/reference/regex/match_replace/)

所以我想我只是 run the example他们提供的功能:

// regex_replace example
#include <iostream>
#include <string>
#include <regex>
#include <iterator>

int main ()
{
  std::string s ("there is a subsequence in the string\n");
  std::regex e ("\\b(sub)([^ ]*)");   // matches words beginning by "sub"

  // using string/c-string (3) version:
  std::cout << std::regex_replace (s,e,"sub-$2");

  // using range/c-string (6) version:
  std::string result;
  std::regex_replace (std::back_inserter(result), s.begin(), s.end(), e, "$2");
  std::cout << result;

  // with flags:
  std::cout << std::regex_replace (s,e,"$1 and $2",std::regex_constants::format_no_copy);
  std::cout << std::endl;

  return 0;
}

但是当我运行它时,我得到了完全相同的错误!

工作示例:http://ideone.com/yEpgXy

所以 ideone.comcplusplus.com 都是错误的。与其用头撞墙试图诊断那些比我聪明得多的人的错误,不如让我保持理智并提出问题。

最佳答案

您需要将编译器更新到 GCC 4.9。

尝试使用 boosts regex作为替代

regex_replace

关于c++ - 如何使用 regex_replace?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24990646/

相关文章:

Python re : why does [, -_] 匹配 "="?

c++ - MSVC++ 2013 中的资源

c++ - 使用指针时的注意事项

c++ - 用整数划分数组项?

c++ - 对重载函数的模糊调用 - std::to_string

javascript - RegExp 与使用简单的正则表达式文字不同

c++ - 全局变量和链接问题

R正则表达式匹配已知字符以外的东西

ruby - 检查低效的正则表达式

javascript - 匹配 Express 中除 '/' 之外的所有路由