【问题标题】:Equivalent to Regex.Replace in C++等效于 C++ 中的 Regex.Replace
【发布时间】:2012-04-24 15:30:00
【问题描述】:

c# 中有 Regex,我可以使用它来删除一些任意字符或字符范围,例如 Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled)。但是什么是 C++ 中的等价物。我知道 Boost 里面有一个正则表达式库。但是对于这个操作,它是否可行以及它的性能如何?在 c++ 中从字符串中删除字符的最佳和快速方法是什么?

【问题讨论】:

  • 这是提升,我会说你不能出错
  • 如果您真的关心性能,请使用Boost.Xpressive(特别是它的静态正则表达式)而不是 Boost.Regex。

标签: c++ gcc boost


【解决方案1】:

你可能想要boost::regex_replace

#include <boost/regex.hpp>
#include <string>

const std::string input; 
boost::regex matcher("[^a-zA-Z0-9_.]+");
const std::string formatter("");

std::string output = boost::regex_replace(input, matcher, formatter);

【讨论】:

    【解决方案2】:

    我使用过 Boost,发现它既快速又易于使用。一个例子:

    #include <boost/regex.hpp>
    
    bool detect_mypattern( const string& text )
    {
        // A specific regex pattern
        static const boost::regex ep("[\\w\\s]{8}\\s{1}\\w{2}\\s{1}Test");
        return( boost::regex_match(text, ep) );
    }
    

    当然,如果您不需要正则表达式的强大功能,还有很多字符串函数可以更快地从字符串中拼接字符。

    【讨论】:

      猜你喜欢
      • 2013-10-30
      • 2011-11-05
      • 2012-01-02
      • 1970-01-01
      • 2012-02-18
      • 2011-01-29
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      相关资源
      最近更新 更多