C ++正则表达式匹配大括号内的内容 [英] C++ regex match content inside curly braces

查看:1798
本文介绍了C ++正则表达式匹配大括号内的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想使用C ++ 11 regex提取匹配的大括号的内容。因此,例如, {foo} 将匹配成功,我可以使用 match_result 提取内容。看起来很简单,但是下面的代码不能做我想做的事情。

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

现在不应该 m [1] 返回只是 foo 没有大括号是否是第一个捕获组?

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

EDIT:这个问题的一个重要信息是,我使用的编译器是GCC 4.6.3(目前是最新的版本在Ubuntu 12.04 LTS )。答案确切地说明了GCC对正则表达式的支持有多差。

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.

推荐答案

你的模式是正确的。你的代码在很大程度上正确,几乎没有'std'在这里和那里(对于'cout','endl'和regex_match),或至少不一致(假设你'使用命名空间std')。

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').

此外,在Visual Studio 2012上,您的代码输出预期的结果。我没有尝试2010年,但我怀疑它也跑在那里(微软在2010年并入TR1)。

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

我怀疑你正在使用gcc。正如@Artyom指出的,在gcc / libstdc ++中没有实现。它编译正常,没有警告,但它给出错误的结果。尽管普遍认为gcc在每个领域都优于微软,但在正则表达式中并不是这样。

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.

在gcc上查找正则表达式的状态:
http://gcc.gnu.org/onlinedocs/ libstdc ++ / manual / status.html#status.iso.200x

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

这篇关于C ++正则表达式匹配大括号内的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆