问题描述
特林得到C ++字符串的正则表达式捕捉工作。我已经试过的Windows Linux的对比四种组合,提升对本地C ++为0x11。样品code是:
的#include<串GT;
#包括LT&;&iostream的GT;
#包括LT&;升压/ regex.hpp>
//#包括LT&;&正则表达式GT;使用命名空间std;
使用名字空间boost;INT主(INT ARGC,字符** argv的)
{
SMATCH SM1;
regex_search(字符串(abhelloworld.jpg),SM1,正则表达式((*),JPG。));
COUT<< SM1 [1];&下; ENDL;
SMATCH SM2;
regex_search(字符串(hell.g),SM2,正则表达式((*)G));
COUT<< SM2 [1];&下; ENDL;
}
这工作最接近的是G ++(4.7)与加速(1.51.0)。在那里,第一COUT输出预期的 abhelloworld。
,但没有从第二COUT。
G ++ 4.7与-std = GNU + 11 <正则表达式>
而不是<升压/ regex.hpp>
不产生输出。
使用本机的Visual Studio 2012 <正则表达式的方式>
就产生不兼容的字符串迭代器异常
Visual Studio 2008中使用升压1.51.0和<升压/ regex.hpp方式>
就产生标准C ++库无效参数异常
难道这些漏洞在C ++中的正则表达式,还是我做错了什么?
gcc doesn't support <regex>
as noted in the other answer. As for the other problems, your problem is you are passing temporary string objects. Change your code to the following:
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;
Your original example compiles because regex_search
takes a const reference which temporary objects can bind to, however, smatch
only stores iterators into your temporary object which no longer exists. The solution is to not pass temporaries.
If you look in the C++ standard at [§ 28.11.3/5], you will find the following:
What this means is that internally, only iterators to your passed in string are used, so if you pass in a temporary, iterators to that temporary object will be used which are invalid and the actual temporary itself is not stored.
这篇关于C ++则字符串捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!