【问题标题】:C++ regex string captureC++ 正则表达式字符串捕获
【发布时间】:2012-08-20 22:36:39
【问题描述】:

让 C++ 正则表达式字符串捕获工作。我已经尝试过 Windows 与 Linux、Boost 与原生 C++ 0x11 的所有四种组合。示例代码为:

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

using namespace std;
using namespace boost;

int main(int argc, char** argv)
{
    smatch sm1;
    regex_search(string("abhelloworld.jpg"), sm1, regex("(.*)jpg"));
    cout << sm1[1] << endl;
    smatch sm2;
    regex_search(string("hell.g"), sm2, regex("(.*)g"));
    cout << sm2[1] << endl;
}

最接近的是 g++ (4.7) 和 Boost (1.51.0)。在那里,第一个 cout 输出预期的 abhelloworld.,但第二个 cout 没有输出。

使用 -std=gnu++11 和 &lt;regex&gt; 而不是 &lt;boost/regex.hpp&gt; 的 g++ 4.7 不会产生任何输出。

使用本机 &lt;regex&gt; 的 Visual Studio 2012 会产生关于不兼容字符串迭代器的异常。

带有 Boost 1.51.0 和 &lt;boost/regex.hpp&gt; 的 Visual Studio 2008 产生关于“标准 C++ 库无效参数”的异常。

这些是 C++ 正则表达式中的错误,还是我做错了什么?

【问题讨论】:

    标签: c++ regex visual-studio boost g++


    【解决方案1】:

    这些是 C++ 正则表达式中的错误,还是我做错了什么?

    在您发帖时,gcc 不支持 &lt;regex&gt;,如另一个答案 (it does now) 中所述。至于其他问题,您的问题是您正在传递 临时字符串对象。将您的代码更改为以下内容:

    smatch sm1;
    string s1("abhelloworld.jpg");
    regex_search(s1, sm1, regex("(.*)jpg"));
    cout << sm1[1] << endl;
    smatch sm2;
    string s2("hell.g");
    regex_search(s2, sm2, regex("(.*)g"));
    cout << sm2[1] << endl;
    

    您的原始示例可以编译,因为 regex_search 采用 const 引用,临时对象可以绑定到该引用,但是,smatch 仅将迭代器存储到不再存在的临时对象中。解决办法是不要通过临时工。

    如果您查看 [§ 28.11.3/5] 中的 C++ 标准,您会发现以下内容:

    返回:regex_search(s.begin(), s.end(), m, e, flags)的结果。

    这意味着在内部,只有 iterators 到你传入的字符串被使用,所以如果你传入一个临时对象,将使用该临时对象的迭代器,这些迭代器是无效的并且是实际的临时对象本身未存储。

    【讨论】:

      【解决方案2】:

      GCC 还不支持&lt;regex&gt;。参考Manual

      【讨论】:

      • 从 gcc4.9 开始,支持 c++11 。
      猜你喜欢
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多