使用C++正则表达式库中的regex_search

Using regex_search from the C++ regex library

本文关键字:regex search C++ 正则表达式 使用      更新时间:2023-10-16

regex_search函数的行为并不像预期的那样。

#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main()
{
    string str = "Hello world";
    const regex rx("Hello");
    cout << regex_search(str.begin(), str.end(), rx) << endl;
    return 0;
}

输出为

0

怎么回事?

正如对该问题的评论中所指出的,C++标准库的旧实现还不支持C++11中的所有功能。当然,libc++是个例外,因为它最初是专门为C++11构建的。

根据这个错误报告,libstdc++中对<regex>的支持仅在GCC的4.9版本中实现。您可以在libstdc++状态页上检查当前状态。

可以确认,您的示例适用于GCC 4.9,但在GCC 4.8中仍然失败。