我对 C++11 正则表达式有点问题,我认为它与贪婪有关。
这是一个小例子。
#include <stdio.h>
#include <string>
#include <regex>
int main (void)
{
std::string in="{ab}{cd}[ef]{gh}[ij][kl]"; // the input-string
std::regex rx1 ("(\\{.+?})(.*)", std::regex::extended); // non-greedy?
std::smatch match;
if (regex_match (in, match, rx1))
{
printf ("\n%s\n", match.str(1).c_str());
}
return 0;
}
我希望
{ab}
用于输出。 但是我得到了
{ab}{cd}[ef]{gh}
如果我贪婪但不使用 ?在.+之后 应该让它成为非贪婪的,对吧?
那么我的想法有什么问题呢? 感谢您的帮助!
克里斯
最佳答案
您需要删除 std::regex::extended
, 它使你的正则表达式 POSIX ERE兼容,并且正则表达式风格不支持惰性量词。
std::regex rx1("(\\{.+?})(.*)");
参见 C++ demo
关于C++11 正则表达式,非贪婪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40674154/