C++ regex match content inside curly braces [duplicate]

浪子不回头ぞ 提交于 2019-12-20 04:31:22

问题


Suppose I would like to do extract the contents of matching curly braces using C++11 regex. So, for example, {foo} would match successfully and I could the use the match_result to extract the contents. It seems simple, but the following code does not quite do what I wish

std::string foo("{foo}");
std::regex r("\\{(.*)\\}");
std::smatch m;
bool result = regex_match(foo, m, r); // result returns true

cout << m[0] << endl; // prints: {foo}
cout << m[1] << endl; // prints: {foo} instead of just foo as I would expect

Now shouldn't m[1] return just foo without the braces given that it is the first capture group?

EDIT: An essential piece of information for this question is that the compiler I'm using is GCC 4.6.3 (which currently is the latest repository version in Ubuntu 12.04 LTS). The answer identifies precisely how poor the support for regex in GCC is.


回答1:


Your pattern is correct. Your code is largely correct with few missing 'std'' here and there (for 'cout', 'endl' and regex_match), or at least inconsistent (assuming you are 'using namespace std').

Moreover, on Visual Studio 2012, your code output the expected result. I didn't try 2010, but I suspect it is running there as well (Microsoft incorporated TR1 back in 2010).

I suspect you are using gcc. As @Artyom pointed out, in gcc/libstdc++ isn't implemented. It compiles fine with no warnings but it gives the wrong results. Despite the common belief that gcc is superior than Microsoft in every area, this isn't the case in regular expression.

Find status of regex on gcc here: http://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.200x



来源:https://stackoverflow.com/questions/13227802/c-regex-match-content-inside-curly-braces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!