【问题标题】:How do I use regex_replace?如何使用 regex_replace?
【发布时间】:2014-07-28 07:46:52
【问题描述】:

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*");
}

这失败了,输出如下:

错误:没有匹配函数调用‘regex_replace(const char*, std::regex, const char [4])

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

不要气馁,我前往 cplusplus.com 并发现我的尝试实际上与 regex_replace 函数的第一个原型非常匹配,所以我很惊讶编译器无法运行它(供您参考: 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 都是错误的。与其把我的头撞在墙上,试图诊断那些比我聪明得多的人的错误,我会放开我的理智去问。

【问题讨论】:

标签: c++ regex


【解决方案1】:

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

尝试使用boosts regex 作为替代

regex_replace

【讨论】:

    【解决方案2】:

    简单代码 C++ 正则表达式_只替换字母数字字符

    #include <iostream>
    #include <regex>
    using namespace std;
    
    int main() {
        const std::regex pattern("[^a-zA-Z0-9.-_]");
        std::string String = "!#!e-ma.il@boomer.zx";
        // std::regex_constants::icase
        // Only first
        // std::string newtext = std::regex_replace( String, pattern, "X", std::regex_constants::format_first_only );
        // All case insensitive
        std::string newtext = std::regex_replace( String, pattern, "", std::regex_constants::icase);
        std::cout << newtext << std::endl;
        return 0;
    }
    

    运行https://ideone.com/CoMq3r

    【讨论】:

      猜你喜欢
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多