繁体   English   中英

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

[英]C++ regex string capture

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;
}

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

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

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

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

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

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

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

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)。

这意味着在内部,只使用传入的字符串的迭代器 ,因此如果传入临时对象,将使用无效的迭代器,并且不存储实际的临时对象。

GCC还不支持<regex> 请参阅手册

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM