C ++正则表达式匹配大括号内的内容

编程入门 行业动态 更新时间:2024-10-26 13:34:55
本文介绍了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上查找正则表达式的状态: gcc.gnu/onlinedocs/ libstdc ++ / manual / status.html#status.iso.200x

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

更多推荐

C ++正则表达式匹配大括号内的内容

本文发布于:2023-11-03 12:21:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555121.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号内   内容   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!