在c++中使用std::regex获得最小匹配

Get smallest match using std::regex in C++

本文关键字:regex std c++      更新时间:2023-10-16

我有这样的代码:

std::smatch m;
std::string dataType = "type = struct A {nint a;nint b;nint c; }";
std::regex_search(dataType, m, std::regex("(= )(.*)( [{]|n|$)"));
std::cout << m.str(2) << std::endl;

问题是它返回最长的匹配,但我需要最小的匹配。输出为:

struct A {n
int a;n
int b;n
int c; }

但必须是:

struct

我怎样才能得到我想要的结果?

可以将.*改为.*?

了解贪婪。

(你真的想在正则表达式中放一个换行符吗?你可能想把它改成\n)

要从文本中获取"struct A",要使用的正则表达式是:

=s(w+sw+)

如果你有其他情况,请给出更多的说明或例子,你的输入和输出应该是什么样子的。

编辑:

感谢user3259253,正确的解决方案是:

\=\s(\w+(\s\w+)?)

正确,使用

std::regex_search(dataType, m, std::regex("(= )(.*)([\{]|\n)$"));
但是,如果您只想捕获=符号和花括号/行尾之间的内容,则不需要那么多()组。这就足够了:
std::regex_search(dataType, m, std::regex("= (.*)[\{]|\n$"));
std::cout << m.str(1) << std::endl;
请注意,这里我们捕获的文本作为第一个条目,m.str(1),而不是第二个条目,因为我们已经消除了"(=)"