C++正则表达式字符串捕获

Mic*_*lak 5 c++ regex boost g++ visual-studio

Tring让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;
}
Run Code Online (Sandbox Code Playgroud)

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

g ++ 4.7 with -std = gnu ++ 11而<regex>不是不<boost/regex.hpp>产生输出.

使用native的Visual Studio 2012会<regex>产生关于不兼容的字符串迭代器的异常.

带有Boost 1.51.0的Visual Studio 2008,并<boost/regex.hpp>产生关于"标准C++库无效参数"的异常.

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

Jes*_*ood 7

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

<regex>如其他答案所述,gcc不支持.至于其他问题,你的问题是你传递的是临时字符串对象.将您的代码更改为以下内容:

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;
Run Code Online (Sandbox Code Playgroud)

您的原始示例进行编译,因为regex_search它采用临时对象可以绑定的const引用,但是,smatch只将迭代器存储到不再存在的临时对象中.解决方案是不通过临时工.

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

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

这意味着在内部,只有迭代器用于你的字符串传递,所以如果你在一个临时通行证,迭代器是临时对象将用于哪些是无效的,实际的临时本身不存储.