试图让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;
}
最接近的可行方案是使用带有Boost (1.51.0)的g++ (4.7)。在这个版本中,第一个cout输出预期值
abhelloworld。
但第二个cout没有任何输出。使用g++ 4.7、-std = gnu++11和
<regex>
而不是<boost/regex.hpp>
并没有产生任何输出。使用Visual Studio 2012原生
<regex>
会导致异常,表示字符串迭代器不兼容。在Boost 1.51.0和
<boost/regex.hpp>
下,使用Visual Studio 2008会导致异常,表示“标准C++库无效参数”。这些问题是由于C++ regex的错误,还是我做错了什么呢?